Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to connect Django container and Spark Container
In my project there are a Django container, running well, and a Spark master container. I try to run a script in django with the call findspark.init(), but it raises an error: ValueError: Couldn't find Spark, make sure SPARK_HOME env is set or Spark is in an expected location (e.g. from homebrew installation). in Django requirements there are findspark, pyspark, pyspark-stubs & py4j, container has jdk installed so. Spark is working on another container, sure, Django can't find Spark because there is not... What is the configuration that allows Django container to connect with Spark container? or where must i set that spark is not local, is on another docker container? How could i set this "expected location" Thanks! my docker-compose: version: '3' services: web: build: . command: bash -c " python manage.py runserver 0.0.0.0:8000 & python manage.py migrate & python manage.py process_tasks" volumes: - .:/code ports: - "8000:8000" - "5556:5556" spark: image: docker.io/bitnami/spark:3-debian-10 environment: - SPARK_MODE=master - SPARK_RPC_AUTHENTICATION_ENABLED=no - SPARK_RPC_ENCRYPTION_ENABLED=no - SPARK_LOCAL_STORAGE_ENCRYPTION_ENABLED=no - SPARK_SSL_ENABLED=no ports: - '8080:8080' -
how to get ManyToMany field data in model save method
class Product(models.Model): varient_property = models.ManyToManyField(to='store.AttributeValue', blank=True) def save(self, *args, **kwargs): super(Product, self).save(*args, **kwargs) # here varient_propery is manytomany field # here i am saving this from django admin panel print(self.varient_property.all()) many to many class class AttributeValue(models.Model): value = models.CharField(max_length=30) available = models.BooleanField(default=True) def __str__(self): return self.value the print statement returns none how can I get many to many data after my model gets save? I want all set many-to-many relations. thanks in advance. -
How to append queried objects from Django database?
I have a model with 2 fields for numbers. I am trying to query those numbers and append them to each others. How do I do that? How do I work with queried objects? This is Model class Post(models.Model): title = models.CharField(max_length=100) num1 = models.IntegerField(blank=True,default=0) num2 = models.IntegerField(blank=True,default=0) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('diary:post-detail', kwargs={'pk': self.pk}) This is view (here I am trying to query and work with queried objects) def home(request): a = Post.objects.values('num1') b = Post.objects.values('num2') result = a + b context = { 'result': result, } return render(request, 'diary/home.html', context) This is a working part of my template {% for x in result %} <p> {{ x }} </p> {% endfor %} This is the error I get TypeError at / unsupported operand type(s) for +: 'QuerySet' and 'QuerySet' C:\Users\detal\Coding\Trading Diary3\TradingDiary\diary\views.py, line 11, in home result = a + b -
Django: How To Only Show Items From One User
I am trying to make a list of posts only from one user so that i can loop through them in the template to display them. How would i write this as a filter? or is that even the best way to do this? views: def collection(request): staff_picks = Collection.objects.filter(author="Staff") context = { 'collections': Collection.objects.all(), 'staff_picks': staff_picks, } return render(request, 'collections.html', context) templates: {% for item in staff_picks %} <div class="collection"> <div class="collection_container"> <div class="collection_image_container"> <a href="{% url 'collectiondetail' item.id %}"><img src="{{ item.collection_image.url }}"></a> </div> <div class="collection_name_container"> {{ item.collection_name }} </div> </div> </div> {% endfor %} </div> -
Django views - can't create object with existing ForeignKey that is an empty string
I have a model that allows having an empty string as a primary key: class District(models.Model): district = models.CharField(max_length=4, primary_key=True, blank=True) I have created one and it exists in the database as an empty string district = '', but when I test a POST request with django views to another model where district is a foreign key I get the below error: This is weird because the view dropdown is clearly referencing the empty string choice. The model where district is foreign key: class OutwardCode(models.Model): area = models.ForeignKey(Area, models.DO_NOTHING) district = models.ForeignKey(District, models.DO_NOTHING) -
Subprocess and os.Popen in django not running under apache with mod_wsgi at Linux Fedora30
I have problem to run Os.Popen and subprocess in django under apache server of linux fedora30 when I run apache I can not run below command with that: command3 = "[ -f /home/mohammad/jointodomain.txt ] || echo 'Username : '%s'\n\nPassword:'%s'\n\nDomain_name:'%s'\n\nDomain_ip:'%s > /home/mohammad/jointodomain.txt " %(username,password,domain_name , domain_ip ) o = os.popen(command3) command4 = "[ -f /home/mohammad/jointodomain.txt ] && echo 'Username : '%s'\n\nPassword:'%s'\n\nDomain_name:'%s'\n\nDomain_ip:'%s > /home/mohammad/jointodomain.txt " %(username,password,domain_name , domain_ip ) o1 = os.popen(command4) These are all jobs that are do : 1. I use Fedora30 2. Then install and update yum and other packeges such below command: yum update sudo systemctl stop firewalld.service yum install python-pip python-devel python3-pip python3-devel pip3 install --upgrade pip pip3 install virtualenv dnf install httpd yum install python3-mod_wsgi.x86_64 3. Then make a directory and install Django on virtual env: mkdir /home/mohammad/myweb1 cd myweb1 virtualenv venv source venv/bin/activate 4. Then pip install below packages: asgiref==3.3.1 Django==3.1.5 psycopg2-binary==2.8.6 python-pam==1.8.4 pytz==2020.5 sqlparse==0.4.1 5. Then config other settings of django : django-admin startproject myproject cd myproject python manage.py startapp main python manage.py collectstatic python manage.py makemigrations python manage.py migrate 6. now config settings.py After these 3 steps I configure settings.py in django: ALLOWED_HOSTS = ['*'] STATIC_ROOT ='/home/mohammad/myweb1/myproject/main/static/' 7. apache config which make django.conf … -
DRF , adding serilizer
Here take a look at my code class GetFollowers(ListAPIView): """ Returns the users who follw user,along with weather the visiter — the one who sent api request — follows them or they follow him/her """ permission_classes = [IsAuthenticated,] pagination_classes = PageNumberPagination serializer_class = FollowersSerilizer def get_queryset(self,*args,**kwargs): print('Error') user = self.request.data.get('user',None) if user is None: raise ValidationError(detail={'user':'This field is required — send as a query_param'}) user, created = User.objects.get_or_create(username=user) if created: raise ValidationError(detail={'user':'Invalid username'}) visiter = self.request.user if user.profile.private: followers_obj, created = Follow.objects.get_or_create(user=user.profile) if not followers_obj.followers.filter(username=user).exists(): raise ValidationError(detail={'Private account':'This account is private , follow the user to access the followers'}) qs = {} #queryset _all_ = [] followers_obj, created = Follow.objects.get_or_create(user=user.profile) all_followers = followers_obj.followers.all() # FOllowers are User instances for follower in all_followers: user_info = [] follower_username = follower.username follower_profile_picture = follower.profile.profile_picture if len(follower.first_name) == 0 and len(follower.slast_name) == 0 : follower_name = follower_username else: follower_name = follower.get_full_name() follower_follows_me = follows(follower,visiter) i_follow_follower = follows(visiter,follower) follower_ispublic = not follower.profile.private user_info.append(follower_username,follower_profile_picture,follower_name,follower_follows_me,i_follow_follower,follower_ispublic) _all_.append(user_info) qs['followers'] = _all_ return qs Now see my serilizer class FollowersSerilizer(serializers.ModelSerializer): class Meta: model = Follow fields = ['followers'] The fields in my queryset , I've got a lot of fields belonging from two serilizers. How do I add a serilizer … -
New Django website on DigitalOcean droplet
I am having a Django website on a DigitalOcean droplet which I uploaded using Nginx Server but I don't know how can I add more Django website on the same droplet and even I can't find any tutorial for the same. Please Help Me! -
Why is the port not being mapped correctly?
I have a Github Action to run some tests in Python. Those tests need a postgressql service, so I create it and map the necessary port. To save time installing some dependencies, I use a docker container to run the action, with the following Dockerfile: FROM ubuntu:16.04 RUN apt update && \ apt install -y gdal-bin python2.7 python-pip git && \ pip install --upgrade pip==9.0.1 EXPOSE 5432 WORKDIR /usr/src/app And for the Github Action, I have the following workflow file: name: Run python tests on: [push] jobs: test: runs-on: ubuntu-16.04 container: image: ghcr.io/myorg/python-unit-tests credentials: username: ${{ github.repository_owner }} password: ${{ secrets.BOT_GITHUB_REGISTRY_TOKEN }} strategy: matrix: group: [1] services: postgres: image: cheewai/postgis:postgres-10.1 env: PG_USER: postgres PG_PASSWORD: postgres POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: test ports: - 5432:5432 options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - uses: actions/checkout@v2 - name: Install dependencies run: | pip install -r requirements.txt pip install -r requirements_dev.txt - name: Prepare database run: | python manage.py migrate --noinput --settings=<somesettings> - name: Running tests (page ${{ matrix.group }}) run: echo 'Run tests¡ With this configuration, it should be working nicely, but when I run it I get the following error: django.db.utils.OperationalError: could not connect to server: Connection refused … -
Django - After overriding the base_site.html, i was unable to publish my post and causing CSRF error
Here is my code for base_site.html {% extends "admin/base.html" %} {% load static %} {% block title %}{% if subtitle %}{{ subtitle }} | {% endif %}{{ title }} | {{ site_title|default:_('Admin') }} {% endblock %} {% block extrastyle %} <style type="text/css"> #branding h1{ color: #fff !important; } #branding h1 a:link, #branding h1 a:visited { color: #fff !important; } .submit-row input{ background-color: #00b388; } #header { background-color: #000000; color: #fff !important; } .module caption{ background-color: #00b388; } div.breadcrumbs { background: #00b388; } .object-tools a.addlink{ background-color: #00b388; } input[type=submit].default, .submit-row input.default{ background-color: #00b388; } </style> {% endblock %} {% block branding %} <form method="post">{% csrf_token %} <h1 id="site-name"><a href="{% url 'admin:index' %}"><img src="{% static 'img/logo.PNG' %}" height="30px" /></a></h1> {% endblock %} {% block nav-global %} {% endblock %} unfortunately i have added the <form> tag in the above code, just to over come with CSRF issue and it does. unfortunately, this approach gives me another error, i.e, i have 3 file fields in my Model, and even though, i have mentioned the files during the upload and when i hit submit, it is not working and keep showing me This field is required error. I am new to Django and your … -
JWT tokens in django: blacklist OutstandingTokens
I'm using following tutorial to use Jwt tokens in my Django application https://medium.com/django-rest/logout-django-rest-framework-eb1b53ac6d35 The LogoutAllView from the tutorial is the following: class LogoutAllView(APIView): permission_classes = (IsAuthenticated,) def post(self, request): tokens = OutstandingToken.objects.filter(user_id=request.user.id) for token in tokens: t, _ = BlacklistedToken.objects.get_or_create(token=token) return Response(status=status.HTTP_205_RESET_CONTENT) I wondered, why it's not possible to use token.blacklist(), like this: class LogoutAllView(APIView): permission_classes = (IsAuthenticated,) def post(self, request): tokens = OutstandingToken.objects.filter(user_id=request.user.id) for token in tokens: token.blacklist() return Response(status=status.HTTP_205_RESET_CONTENT) When I try this I get following error: AttributeError: 'OutstandingToken' object has no attribute 'blacklist' It seems like blacklist() is only possible with refreshtokens. Why is this not possible with outstanding tokens? As the function is: class BlacklistMixin: """ If the `rest_framework_simplejwt.token_blacklist` app was configured to be used, tokens created from `BlacklistMixin` subclasses will insert themselves into an outstanding token list and also check for their membership in a token blacklist. """ if 'rest_framework_simplejwt.token_blacklist' in settings.INSTALLED_APPS: def verify(self, *args, **kwargs): self.check_blacklist() super().verify(*args, **kwargs) def blacklist(self): """ Ensures this token is included in the outstanding token list and adds it to the blacklist. """ jti = self.payload[api_settings.JTI_CLAIM] exp = self.payload['exp'] # Ensure outstanding token exists with given jti token, _ = OutstandingToken.objects.get_or_create( jti=jti, defaults={ 'token': str(self), 'expires_at': datetime_from_epoch(exp), }, ) … -
Call external library command as celery task
I'm using following tutorial for using JWT tokens in my Django application: https://medium.com/django-rest/logout-django-rest-framework-eb1b53ac6d35 the LogoutAllView is as following: class LogoutAllView(APIView): permission_classes = (IsAuthenticated,) def post(self, request): tokens = OutstandingToken.objects.filter(user_id=request.user.id) for token in tokens: t, _ = BlacklistedToken.objects.get_or_create(token=token) return Response(status=status.HTTP_205_RESET_CONTENT) Now I wondered, is it not possible to do it like this: class LogoutAllView(APIView): permission_classes = (IsAuthenticated,) def post(self, request): tokens = OutstandingToken.objects.filter(user_id=request.user.id) for token in tokens: token.blacklist() return Response(status=status.HTTP_205_RESET_CONTENT) As the function blacklist is the following: class BlacklistMixin: """ If the `rest_framework_simplejwt.token_blacklist` app was configured to be used, tokens created from `BlacklistMixin` subclasses will insert themselves into an outstanding token list and also check for their membership in a token blacklist. """ if 'rest_framework_simplejwt.token_blacklist' in settings.INSTALLED_APPS: def verify(self, *args, **kwargs): self.check_blacklist() super().verify(*args, **kwargs) def blacklist(self): """ Ensures this token is included in the outstanding token list and adds it to the blacklist. """ jti = self.payload[api_settings.JTI_CLAIM] exp = self.payload['exp'] # Ensure outstanding token exists with given jti token, _ = OutstandingToken.objects.get_or_create( jti=jti, defaults={ 'token': str(self), 'expires_at': datetime_from_epoch(exp), }, ) return BlacklistedToken.objects.get_or_create(token=token) But when I try this I get following error: AttributeError: 'OutstandingToken' object has no attribute 'blacklist' I'm not that used to using jwt tokens. But it seems that the … -
Django, update_session_auth_hash not working
I made an api to change the user password, following this tutorial: https://medium.com/django-rest/django-rest-framework-change-password-and-update-profile-1db0c144c0a3 However, I don't want the user to be logged out and tried using the function update_session_auth_hash(request, user). I tried several things, but the user keeps logging out: Option 1 Function in the serializer: ## serializer def update(self, instance, validated_data): instance.set_password(validated_data['password']) instance.save() request = self.context['request'] user = request.user update_session_auth_hash(request, user) return instance Option 2 Function in the view # serializer def save(self, **kwargs): password = self.validated_data['password'] user = self.context['request'].user user.set_password(password) user.save() return user # views: class ChangePasswordView(generics.UpdateAPIView): queryset = User.objects.all() permission_classes = [IsAuthenticated,] serializer_class = ChangePasswordSerializer def update(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() update_session_auth_hash(request, request.user) return Response({'ok'}) However neither 1 nor 2 are working, what am I doing wrong? -
Best approach to build a dashboard in djnago [closed]
I'm working on a project : Web Aplication, that tracks & manage sales. i'm wondering what is the effecient way to build dashboards with several graphs! for example should i have the graphs configurations in the html template or can i write them in the views.py functions? also if i can have a class in the views.py with several functions (each function correspond to a graph) that renders in the same template? Appreciate any guidances in this regard! Thanks a lot! -
Image is not Editing after selecting
I am going through a Django Tutorial. I am building a feature of Image Crop in my Blog App. BUT my selected image is not Editing. Here is my Code :- views.py #PAGE FOR EDIT PROFILE PHOTO. def edit_photo(request): if request.method == 'POST': photo_form = EditProfilePhoto(request.POST, request.FILES, instance=request.user.profile) if photo_form.is_valid(): custom_form = photo_form.save(False) custom_form.save() return redirect('/') else: photo_form = EditProfilePhoto(instance=request.user.profile) args = {} args['photo_form'] = photo_form return render(request, 'mains/edit_photo.html' , args) models.py Class Profile(models.Model): name = models.CharField(max_length=22) user = models.ForeignKey(User,on_delete=models.CASCADE) image = models.ImageField(upload_to='images') forms.py class EditProfilePhoto(forms.ModelForm): class Meta: model = Profile fields = ['image',] widgets = {'image' : forms.FileInput} base.html {% load static %} <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- favicon --> <link rel="shortcut icon" type="image/jpg" href="{% static 'favicon.ico' %}"/> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384- TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <!-- jquery --> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <!-- cropper --> <script src="https://cdnjs.cloudflare.com/ajax/libs/cropper/4.1.0/cropper.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropper/4.1.0/cropper.min.css"> <!-- custom css & js--> <link rel="stylesheet" href={% static 'style.css' %}> <script src={% static 'main.js' %} defer></script> <title>image cropper</title> </head> <body> <div class="container mt-3"> </div> </body> </html> <p> main.js ( File in static folder in Project Directory ) const alertBox = document.getElementById('alert-box') const imageBox = … -
Create htaccess file for domain redirection (Django app deployed in Heroku)
Situation: I've bought a specific domain, let's say 'example.ch' for my Django application which is deployed in Heroku. I also created an automated SSL certificate on Heroku (ACM). This certificate is valid for the WWW-subdomain, i.e. ACM Status says 'OK'. It fails for the non-WWW root domain, so I deleted the root domain entry on Heroku. Issue: When I type 'https://www.example.ch' in the browser, I find my secure webpage and everything is fine. When I type 'www.example.ch' in the browser, I find my webpage but it is not secure When I type 'example.ch' in the browser, the webpage cannot be found. Goal: I would like to type 'www.example.ch' as well as 'example.ch' in the browser to be always redirected to 'https://www.example.ch'. Approach (so far): My Host (swizzonic.ch) does not allow for 'Alias' records. 'A' records are possible but not supported by Heroku (https://help.heroku.com/NH44MODG/my-root-domain-isn-t-working-what-s-wrong). Swizzonic support told me to use a htaccess-file for redirection. As I understand so far, I have to extend my middleware accordingly (?). Note that I use the common options for SSL redirection (SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https'), SECURE_SSL_REDIRECT = True, SESSION_COOKIE_SECURE = True, CSRF_COOKIE_SECURE = True). How can I create a htaccess-file, where do I have to … -
Reverse with Argument Not Found in Django
I've been using Django for a while and at this moment I'm trying to create an edit page. My problem is that now that as soon my link is in my CSS.html file, I can't even access my CSS.html file (with my browser). It just shows the error message. The hyperlink in my CSS.html file <a href="{% url 'edit' name %}">{{ name }}</a> My path in my urls.py file path("edit/str:name>/", views.edit, name="edit") My function to render the edit page in views.py: def edit(request, name): entry = util.get_entry(name) return render(request, "encyclopedia/edit.html", { "name": name, "entry": entry}) My error: Reverse for 'edit' with arguments '('CSS',)' not found. 1 pattern(s) tried: ['edit/str:name>/$'] Thank you in advance! -
no signature found for builtin type <class 'filter'>
I am implementing django_filters on my project. Model: class MsTune(models.Model): class Meta: app_label = "myapp" name = models.CharField(max_length=255) class MsTuneFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_expr='iexact') class Meta: model = MsTune fields = [myfields...] View: def MsTuneList(request): mstunes = MsTune.objects.all() f = MsTuneFilter(request.GET, queryset=MsTune.objects.all()) return render(request, 'manuscript/mstune_list.html', {'mstunes': mstunes, 'filter': filter}) When I point my browser to my template I get this error: ValueError at /testdb/mstunes/ no signature found for builtin type <class 'filter'> Request Method: GET Request URL: .../mstunes/ Django Version: 3.1.5 Exception Type: ValueError Exception Value: no signature found for builtin type <class 'filter'> Exception Location: /usr/lib/python3.7/inspect.py, line 2364, in _signature_from_callable I already successfully used django_filters on another project, so I'm not sure what the issue with this one is. I'm using the latest Django version 3.1 on Python 3.7. -
Permission that current user can request info only about itself Django?
How to implement permission that current user can read info only about it self? For example, current logged user id is 69909317-bd29-47b8-8878-5884182e4948 and i want request user/69909317-bd29-47b8-8878-5884182e4948 to read info about current user. I tried something like class IsOwner(permissions.BasePermission): def has_object_permission(self, request, view, obj): return obj.owner == request.user But fell in error that User object has no attribute owner -
Clear AWS SES email queue
My Django server ran into an error during the night and sent me thousands upon thousands of error logs by emails (several per second). I patched the error and rebooted the server, but I am still receiving emails, dated from several hours ago. How can I stop the old emails from being sent? Is there a way to tell amazon SES to clear its queue of email? -
how can I make the choice of cities inside of specific region in Django admin?
I am a beginner in Django Frame work.enter image description here when I click to the regions it should display all the available regions and after choosing specific region, inside that region it is available to choose a specific city -
Add Serializer data in a coulmn of same id rest api
I have 50 questions with options. every time user select one option i recieve api in post method in views.py format below { "question_id": 1, "user_id": 1, "response": "Agree_5", "category": "A" } As of now i was able to store this data in my postgresql table="paresponses" but one row at a time i.e user_id|question_id|response |category 1 | 1 |Agree_5 | E 1 | 2 |Diagree_1| A but now i need to store like this in a new table="user_responses" user_id|question_1|question_2|question3|...... 1 |Agree_5 |disagree_1|..... 2 |Agree_5 |diagree_1 |..... I dont need "category" parameter so that is fine . views.py @api_view(['GET', 'POST']) def AnswersList(request): if request.method == 'GET': # user requesting data snippets = PAResponse.objects.all() serializer = PAAnswersSerializer(snippets, many=True) return Response(serializer.data) elif request.method == 'POST': # user posting data serializer = PAAnswersSerializer(data=request.data) print("serializer in post",type(serializer),serializer) if serializer.is_valid(): serializer.save() # save to db result=Calculate(serializer) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py class PAAnswersSerializer(serializers.ModelSerializer): class Meta: model=PAResponse fields='__all__' Models.py class PAResponse(models.Model): user_id=models.IntegerField() question_id=models.IntegerField(primary_key=True) response=models.CharField(max_length=255) category=models.CharField(max_length=100) class Meta: db_table="paresponses" def __str__(self): return self.response How can i acheive this please give me a lead . i receive api one by one after every question selected with above details. Any kind of suggestion and lead is aprreciated . … -
handling different forms post request on single page -Django
I am a newbie, and I am working on a website. On this website I have created admin panel to manage different products and attributes . I have a page named size.html and and I am supposed to change it name and make it productAtributes.html and on this single page I want to do all add, update, delete operations for different Product attributes. My code is as: 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 Color(models.Model): color_id = models.AutoField("Color ID", primary_key=True, auto_created=True) prod_color = models.CharField("Product Color", max_length=50, null=False) def __str__(self): return "{color_id}-->{prod_color}".format(color_id=self.color_id, prod_color=self.prod_color) class PaperChoice(models.Model): paper_id = models.AutoField("Paper Choice ID", primary_key=True, auto_created=True) paper_choices_name = models.CharField("Paper Choices", max_length=50, null=False) def __str__(self): return "{}-->{}".format(self.paper_id, self.paper_choices_name) views.py from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage from django.shortcuts import render, redirect from user.models import * def size(request): if request.method == 'POST': size_store = request.POST['prod_size'] size_update = Size(prod_size=size_store) size_update.save() return redirect('/admin1/productSize') else: size_show = Size.objects.all() # start paginator logic paginator … -
How to create a objects with related tables
I'm building a django web app and I'm having troubles in inserting news objects(musics) without using forms. I will give an example of what I've so far: here is my models.py: from django.db import models from django.contrib.auth.models import User class Genre(models.Model): genre=models.CharField(max_length=250) def __str__(self): return str(selt.genre) class Music(models.Model): author=models.OneToOneField(User, on_delete=models.CASCADE) genre=models.ForeignKey(Genre, on_delete=models.CASCADE) title=models.CharField(max_length=100) audio_file=models.FileField(upload_to='songs/') cover=models.ImageField(upload_to='covers/') and here is my views.py: from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse from .models import * def add_song(request): if request.method=='post' or request.FILES: genre=request.post['genre'] #getting the genre data from html template title=request.post['title'] #getting the title from html template audio_file=request.files['audio_file'] cover=request.files['cover'] instance=request.user genre_selected=Genre.objects.get(genre=genre) #to get the genres already inserted in the db music=Music.objects.create(author=instance, title=title, genre=genre_selected, audio_file=audio_file, cover=cover) return redirect('/') else: return render(request, 'music.html') And when I try to add new always I get this error: Cannot assign "<Genre: Pop>": "Music.genre" must be a "Genre" instance. Can you guys help me out? -
How to develop Analytical Dashboard using django
I'm working on the project of Analytical Dashboard Web application. In this application user need to import data from datasource like server,local,drive. I don't want to import data from model. Is it possible in django-analytical. Request your suggestion.