Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django&REST-framework architecture
Hello I am tasked with translating a current Excel tool to a web application. I decided to use Python and Django. Lately I studied the Django REST framework. I have the following related questions. Is it for such an application a good idea to first write a web REST API so that I firstly only need to focus on the backbone of the web application. I.e. implement the PUT, POST, GET and DELETE methods and the Django models. The second step would be to implement the user interface... But if this is a valid method how can I reuse the REST views??? I followed the REST tutorials, but they don't show how to build a nice slick user-interface on top of the REST API. Since REST views inherit from Django, I think it's maybe not such a good idea to write a Django view which inherits from a REST Apiview? Or can I directly use an API endpoint in a template. If so where can I get some nice examples? -
Django: Graphviz generation with model names only?
I'm using Graphviz in Django (via django-extensions) to generate graph models. I'd like to generate graphs in two distinct ways: App by app in details (1 app per graph) -> no problem, it's done. All my models from all my apps, but without attributes (only model names) -> is it possible? I didn't find a way to do it in the documentation. If there is no way, I guess I could take a look to the source code, but not sure about the difficulty to do this. Thanks. -
Images are not displayed on web-page (Django)
the problem is this, using Bootstrap 3, created the "Carousel" from the images, then in Views wrote a loop that adds all the images with paths to the dictionary, then through the loop, output all the images in HTML-views. HTML <div id="myCarousel" class="carousel slide" data-ride="carousel"> <!-- Indicators --> <ol class="carousel-indicators"> <li data-target="#myCarousel" data-slide-to="0" class="active"></li> <li data-target="#myCarousel" data-slide-to="1"></li> <li data-target="#myCarousel" data-slide-to="2"></li> </ol> <!-- Wrapper for slides --> <div class="carousel-inner"> {% for picture in picture_list %} <div class="item active"><img src="{{ picture }}" style="width:100%;"> </div> {% endfor %} </div> <!-- Left and right controls --> <a class="left carousel-control" href="#myCarousel" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left"></span> <span class="sr-only">Previous</span> </a> <a class="right carousel-control" href="#myCarousel" data-slide="next"> <span class="glyphicon glyphicon-chevron-right"></span> <span class="sr-only">Next</span> </a> Views def recipes_list(request): recipes = Recipe.objects.filter(created_date__lte=timezone.now()).order_by('created_date') pictures = os.listdir(os.path.join(settings.STATIC_PATH, 'images/carousel')) picture_list = [] for picture in pictures: path = str(os.path.join(settings.STATIC_PATH, 'images\carousel').replace('\\', '/')) picture_list.append('%s/%s' % (path, picture)) return render(request, 'Recipes/recipes_list.html', {'recipes': recipes, 'sub_form': sub_form, 'picture_list': picture_list}) In browser <img src="C:/Users/%username%/PycharmProjects/Django/CookBook/Recipes/static/images/carousel/FRIED SAGE1.jpg" style="width:100%;"> -
save polygon wkt in HEX mode in database
I want to have a fixture (in django) to have some regions' polygon. In my database a long string is saved (type geometry and HEX), however I have a wkt (starting with SRID=4326;MULTIPOLYGON(((45.09 ...... ) for the regions. how can I do that? tnx -
Query different field than defined in return for a ManyToMany field option
I am new to Django and have a problem that I am trying to fix. In my application I have a model Asset which has multiple choice answer from AFF. Here is the code: class Rtype(models.Model): rtype_name = models.CharField(max_length=10, verbose_name="Type", default = "") rtype_score = models.CharField(max_length=10, verbose_name="Score", default = "") def __str__(self): return self.rtype_name class AFF(models.Model): ff = models.CharField(max_length=100, verbose_name="FF", default = "") ff_score = models.ForeignKey(Rtype, on_delete=models.CASCADE, blank=True, null=True, verbose_name="Score", default = "") def __str__(self): return self.ff class Asset(models.Model): fjam = models.ManyToManyField(AFF, verbose_name="Fjam", default = "", blank=True) def __str__(self): return self.fjam Let's say there are following entries in the database: rtype_name = Critical rtype_score = 5 rtype_name = Medium rtype_score = 3 ff = Direct ff_score = Critical ff = Indirect ff_score = Medium If user chooses in Asset form, both Direct and Indirect, how can I save 3 + 5 in the database when they submit the form instead of rtype_names by keeping return self.rtype_name in Rtype (useful for showing user a name rather then a score). -
DJongo adding Custom user field error in DJango 2
I used DJongo for using mongodb with Django2. When I adding custom fields for user, I get following erorr: "jomploy_user"."first_name", "jomploy_user"."last_name", "jomploy_user"."email", "jomploy_user"."is_staff", "jomploy_user"."is_active", "jomploy_user"."date_joined", "jomploy_user"."telephone" FROM "jomploy_user" WHERE "jomploy_user"."id" = %(0)s Version: 1.2.20 Request Method: GET Request URL: http://127.0.0.1:8000/admin/jomploy/user/1/change/ Django Version: 2.0.2 Exception Type: SQLDecodeError Exception Value: FAILED SQL: SELECT "jomploy_user"."id", "jomploy_user"."password", "jomploy_user"."last_login", "jomploy_user"."is_superuser", "jomploy_user"."username", "jomploy_user"."first_name", "jomploy_user"."last_name", "jomploy_user"."email", "jomploy_user"."is_staff", "jomploy_user"."is_active", "jomploy_user"."date_joined", "jomploy_user"."telephone" FROM "jomploy_user" WHERE "jomploy_user"."id" = %(0)s Version: 1.2.20 Exception Location: E:\Django\lib\site-packages\djongo\sql2mongo\query.py in __iter__, line 451 Python Executable: E:\Django\Scripts\python.exe Python Version: 3.6.2 Python Path: ['E:\\Project\\fuck6', 'E:\\Django\\Scripts\\python36.zip', 'E:\\Django\\DLLs', 'E:\\Django\\lib', 'E:\\Django\\Scripts', 'C:\\Program Files\\Python36\\Lib', 'C:\\Program Files\\Python36\\DLLs', 'E:\\Django', 'E:\\Django\\lib\\site-packages', 'C:\\Program Files\\Python36', 'C:\\Program Files\\Python36\\lib\\site-packages'] Server time: Sun, 18 Feb 2018 09:45:25 +0000 And here is my code: class User(AbstractUser): telephone = models.CharField(max_length=15,blank=True,null=True) -
How to return a list foreign key fields in a raw form using SerializerMethodField in Django Rest Framework?
Models: class Author(models.Model): name = models.CharField() class Book(models.Model): author = models.ForeignKey("Author") title = models.CharField() subtitle = models.CharField() def get_full_title(self): return "{title}: {subtitle}.".format(title=self.title, subtitle=self.subtitle) Queryset: queryset = Author.prefetch_related("book_set").all() Desired Responce: [ { "id": 1, "name": "J. R. R. Tolkien", "books": [ "The Hobbit: or There and Back Again", "The Fellowship of the Ring: being the first part of The Lord of the Rings.", "The Two Towers: being the second part of The Lord of the Rings.", "The Return of the King: being the third part of The Lord of the Rings." ] }, { "id": 2, "name": "Peter Thiel", "books": [ "The Diversity Myth: Multiculturalism and Political Intolerance on Campus.", "Zero to One: Notes on Startups, or How to Build the Future." ] } ] The problem here is that if you use serializers.ListSerializer() on Authors.book_set list, I will get an entire model in that list with all it's fields. If you try to use serializers.SerializerMethodField, DRF would not let you use it on multiple results. SerializerMethodField doesn't support an option many AKA serializers.SerializerMethodField(many=True) I should note here that one could write a method that cycles through the results and accumulates them into a string, but that limits you from further … -
Django, User can have more than one role in the application, 3 types of User
As title, I have 3 types of User and each User can have more than one role. from django.contrib.auth.models import AbstractUser, User from django.db import models from django.db.models import CASCADE from hospital.models import Hospital class Role(models.Model): ''' The Role entries are managed by the system, automatically created via a Django data migration. ''' DOCTOR = 1 DIRECTOR = 2 PATIENT = 3 ROLE_CHOICES = ( (DOCTOR, 'doctor'), (DIRECTOR, 'director'), (PATIENT, 'patient'), ) id = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, primary_key=True) def __str__(self): return self.get_id_display() class User(AbstractUser): roles = models.ManyToManyField(Role) def __str__(self): return self.roles class Doctor(models.Model): # role = models.OneToOneField(User, on_delete=CASCADE) career = models.TextField(blank=True, max_length = 1000) class Director(models.Model): # role = models.OneToOneField(User, on_delete=CASCADE) members = models.ManyToManyField(Doctor) class Patient(models.Model): # personal information like above. https://simpleisbetterthancomplex.com/tutorial/2018/01/18/how-to-implement-multiple-user-types-with-django.html I'm creating a model, but I do not know how to set the key. I made it by referring to the above site. The director owns the doctor and can authorize it. But I do not know how to give a key to a doctor or director. If you I to comment, I get an error. I hope you can help me. -
how to add post to django user model using foreignkey
i created a model class ThisUser(models.Model): created = models.DateTimeField(auto_now=True) message = models.CharField(max_length=120) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.user I want to store message specifically for the user who is authenticated. right now this will give me all user who is available in my user model. Please help -
ImportError in django
I am learning django. I am doing exactly what had said in tutorial book. I am getting this error no matter what I do. please help me to fix this. please don't mind of grammatical error in my description. 1st step:django-admin startproject project 2nd step:cd project 3rd step:django-admin startapp myapp 4th step:cd to myproject 5th step:nano settings.py 6th step:add myapp in install app list 7th step:edit urls.py file add the below code for url mapping from django.conf.urls import include, url from django.contrib import admin admin.autodiscover() urlpatterns = [ # Examples: # url(r'^$', 'project.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^chirag/','myapp.views.chirag',name='chirag'),] 8th step:move back to myapp and edit views.py file as below: from django.shortcuts import render from djanog.http import HttpResponse # Create your views here. def chirag(request): t="""<h1>hello chirag<h1>""" return HttpResponse(t) 9th step:move back to project folder then run a code python manage.py syncdb 10th step:create a super user 11nth step:python manage.py migrate 12th step:python manage.py runserver: Performing system checks... System check identified no issues (0 silenced). February 18, 2018 - 08:18:29 Django version 1.8, using settings 'project.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. 13th step:open a web-browser then type:http://127.0.0.1:8000/chirag then i am getting this error ImportError … -
Cannot assign "''": "User.country" must be a "Country" instance
I am using a custom register serializer in django-rest-auth to add new fields on registration. I have a country model and a country field in the user model that is an FK to countries. user.models @python_2_unicode_compatible class User(AbstractUser): phone = models.CharField(max_length=15, null=True) verified_phone = models.BooleanField(default=False) country = models.ForeignKey(Country, related_name='country') level = models.ForeignKey(UserLevel, related_name='user_level') user.serializers class UserModelSerializer(HyperlinkedModelSerializer): class Meta: model = User country = serializers.ReadOnlyField(source='country.name') fields = [ 'url', 'id', 'username', 'country', 'email', 'phone', ] read_only_fields = ( 'id', 'password', ) custom register serializer class CustomRegisterSerializer(RegisterSerializer): country = serializers.PrimaryKeyRelatedField(read_only=True) def get_cleaned_data(self): return { 'country': self.validated_data.get('country', ''), 'password1': self.validated_data.get('password1', ''), 'email': self.validated_data.get('email', ''), 'username': self.validated_data.get('username', ''), } def save(self, request): print(self.get_cleaned_data()) adapter = get_adapter() user = adapter.new_user(request) user.country = self.validated_data.get('country', '') self.cleaned_data = self.get_cleaned_data() adapter.save_user(request, user, self) setup_user_email(request, user, []) user.save() return user Sample data that is sent from the client with the country as an object {username: "bernie", email: "bernie@d.com", country: {…}, password1: "password", password2: "password"} but this error keeps coming, Cannot assign "''": "User.country" must be a "Country" instance. when I printed the request on the console this is what I got {'country': '', 'password1': 'password', 'email': 'bernie@d.com', 'username': 'bernie'} which means that somewhere along the line, the country data … -
only part of task executed when connection lost on redis using django celery
I have a django celery task that is only partly executing. I start up the app and the connection looks good: INFO/MainProcess] Connected to redis://elasticache.cache.amazonaws.com:6379/0 [2018-02-17 23:27:24,314: INFO/MainProcess] mingle: searching for neighbors [2018-02-17 23:27:25,339: INFO/MainProcess] mingle: all alone [2018-02-17 23:27:25,604: INFO/MainProcess] worker1@test_vmstracker_com ready. I initiate the process and the task is received an executed: [2018-02-17 23:27:49,810: INFO/MainProcess] Received task: tracking.tasks.escalate[92f54d48202] ETA:[2018-02-18 07:27:59.797380+00:00] [2018-02-17 23:27:49,830: INFO/MainProcess] Received task: tracking.tasks.escalate[09a0aebef72b] ETA:[2018-02-18 07:28:19.809712+00:00] [2018-02-17 23:28:00,205: WARNING/ForkPoolWorker-7] -my app is working- Then I start getting errors and it doesn't finish the task where my app sends an email [2018-02-17 23:28:00,214: ERROR/ForkPoolWorker-7] Connection to Redis lost: Retry (0/20) now. [2018-02-17 23:28:00,220: ERROR/ForkPoolWorker-7] Connection to Redis lost: Retry (1/2 Does anyone know why only have executes and then the connection is lost? Here is the full stacktrace: [2018-02-17 23:28:19,382: WARNING/ForkPoolWorker-7] /usr/local/lib/python3.6/site-packages/celery/app/trace.py:549: RuntimeWarning: Exception raised outside body: ConnectionError("Error while reading from socket: ('Connection closed by server.',)",): Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/redis/connection.py", line 177, in _read_from_socket raise socket.error(SERVER_CLOSED_CONNECTION_ERROR) OSError: Connection closed by server. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/redis/client.py", line 2879, in execute return execute(conn, stack, raise_on_error) File "/usr/local/lib/python3.6/site-packages/redis/client.py", line 2764, in _execute_transaction self.parse_response(connection, '_') File … -
How do I replace content with other content in a Django template?
I am iterating over my model and I wanted to replace that list with content from same model, only sorted, just by using a button. Let's presume I have this: <div class="col-md-3"> <button>Replace content </button> </div <div class="col-md-9"> {% for c in cats%} {{c.name}} {% endfor %} <p>Content to be replaced</p> </div> <div class="col-md-9"> {% for c in animal.cats_set.all %} {{c.name}} {% endfor %} <p>Content to replace above content, sorted by if cat belongs to same animal</p> </div> How would I replace the content with the second content in this case ? Im thinking about a jQuery. -
ListField not found error in django
I am trying to use mongodb with django. My main poject name is 'mysite' and inside that there is an app named 'blog' and inside blog/models.py, I have written the following portion. from django.db import models from djangotoolbox.fields import ListField class Post(models.Model): title = models.CharField() text = models.TextField() tags = ListField() comments = ListField() I have installed djangotoolbox. When I run the command on python shell from blog.models import Post It shows the following error. >>> from blog.models import Post Traceback (most recent call last): File "<console>", line 1, in <module> File "E:\Study\mysite\blog\models.py", line 2, in <module> from djangotoolbox.fields import ListField File "C:\Program Files (x86)\Python36-32\Lib\site-packages\djangotoolbox\fields.py", line 4, in <module> from django.utils.importlib import import_module ModuleNotFoundError: No module named 'django.utils.importlib' >>> Why is this error occurring? and what is its solution? Because I have seen all over the internet and could not find any. -
I don't know how to render entries of my models properly in Django template
I have a Course model from which I render my courses in the template. It also allows me to paginate or search through them. But I also want to sort the courses by faculty or by study programme (other models) and be able to paginate or search through them as well. Basically I want that by clicking, for example, on faculty name on the left column, the content on right column will be replaced with the courses of that faculty, and they will also have pagination and be searchable. I think is easy, but I don't have any idea yet. def index(request): query_list = Course.objects.all() query = request.GET.get('q') if query: query_list = query_list.filter(Q(name__icontains=query)) paginator = Paginator(query_list, 1) page = request.GET.get('page') try: courses = paginator.page(page) except PageNotAnInteger: courses = paginator.page(1) except EmptyPage: courses = paginator.page(paginator.num_pages) context = { 'courses': courses, 'faculties': Faculty.objects.all(), 'departments': Department.objects.all(), 'studies': StudyProgramme.objects.all(), 'teachers': Teacher.objects.all() } return render(request, 'courses/index.html', context) <div class="container-fluid"> <div class="row"> <div class="col-md-3"> <div class="jumbotron"> <h4>Sort courses</h4> <hr> <br> <ul> {% for faculty in faculties %} <li><a href=""> {{ faculty.name }}</a></li> {% for department in faculty.department_set.all %} {% for study in studies %} <ul> {% if study.department == department %} <li>{{ study.name }}</li> {% endif … -
Django querying lists in Postgres JSONField
For the below given model, from django.contrib.postgres.fields import JSONField from django.db import models class Dog(models.Model): name = models.CharField(max_length=200) data = JSONField() def __str__(self): return self.name I have created an object as follows. Dog.objects.create( name='Rufus', data=[ { 'owner': 'Bob', }, { 'owner': 'Rob', }, ]) I want to query if the dog was owned by the given person, since the data is list how do I query if the list consists given value? >>> Dog.objects.filter(data__0__owner='Bob') ... <QuerySet [<Dog: Rufus>]> >>> Dog.objects.filter(data__0__owner='Rob') ... <QuerySet []> My Required result is, >>> Dog.objects.filter(query_on_data_to_know_if_the_given_person_is_owner='Rob') ... <QuerySet [<Dog: Rufus>]> -
Django logging in error- log in form does not log user in
When I try to log in as a user I can enter the username and password into the form and it continues to the next page, but it doesn't actually sign the user in. Where is my issue? login.html file: {% extends 'teammanager/base.html' %} {% block title %}Login{% endblock %} {% block content %} <h2>Login</h2> <form action="/profile/" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Login</button> </form> {% endblock %} -
InvalidRequestError: This customer has no attached payment source
I've been following the Quickstart guides from Stripe. https://stripe.com/docs/quickstart https://stripe.com/docs/subscriptions/quickstart I have this code at the bottom of my subscription form. <script type="text/javascript"> var displayError= document.getElementById('card-errors'); var stripe= Stripe("pk_test_BjhejGz5DZNcSHUVaqoipMtF"); var elements= stripe.elements(); var style= { base: { fontSize: "1.1875rem", fontSmoothing: "always", fontWeight: "600" } }; var card= elements.create("card",{style:style}); card.mount("#card-element"); card.addEventListener('change', function(event) { if (event.error) { displayError.textContent = event.error.message; } else { displayError.textContent = ''; } }); var formID= "register-form"; var form= document.getElementById(formID); form.addEventListener("submit",function(event){ event.preventDefault(); stripe.createToken(card).then(function(result){ if(result.error) { displayError.textContent= result.error.message; } else { stripeTokenHandler(result.token, formID); } }) }); function stripeTokenHandler(token, formID) { // Insert the token ID into the form so it gets submitted to the server var form = document.getElementById(formID); var hiddenInput = document.createElement('input'); hiddenInput.setAttribute('type', 'hidden'); hiddenInput.setAttribute('name', 'stripeToken'); hiddenInput.setAttribute('value', token.id); form.appendChild(hiddenInput); // Submit the form form.submit(); } </script> Then my views.py has this: if registration_form.is_valid(): stripe.api_key= "sk_test_8rdFokhVsbsJJysHeKgyrMTc" stripeCustomer= stripe.Customer.create( email=request.POST["username"], ) subscription= stripe.Subscription.create( customer=stripeCustomer["id"], items=[{"plan":"plan_CLFfBrRAKl7TRt"}], ) This gives me an error: Internal Server Error: /login-register/ Traceback (most recent call last): File "/home/myUserName/myDjangoProjectWithStripe/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 42, in inner response = get_response(request) File "/home/myUserName/myDjangoProjectWithStripe/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/home/myUserName/myDjangoProjectWithStripe/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 178, in _get_response response = middleware_method(request, callback, callback_args, callback_kwargs) File "/home/myUserName/myDjangoProjectWithStripe/local/lib/python2.7/site-packages/mezzanine/pages/middleware.py", line 98, in process_view return view_func(request, *view_args, **view_kwargs) … -
Auto pass or recieve a ForeignKey instance value
Say I have a Profile Model that gets created automatically from auth.models.User by using signals and on the Profile model OneToOneField, I have a company attribute tied to a Company model by ForeignKey. Meanwhile this Company model gets created at signup too via Foreignkey using formset_factory in views. What I am aiming to achieve is having the Company instance created at signup passed to the Profile instance Foreignkey as well. Tried using signals, overiding save methods etc. doesn't seem to be working. Here's a sample code, all suggestions are greatly appreciated in advance. from django.contrib.auth.models import User class Company(models.Model): comp_admin = model.ForeignKey(User, on_delete=models.CASCADE) comp_name = models.CharField(max_length=200) ............................. ............................. other attributes omitted ............................. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) company = models.ForeignKey(Company, on_delete=models.CASCADE) -
How to pull information saved from IP address call with GeoIP2() django models to display in my html
I have made function that gets the IP address and stores information from the city_data in GeoIP2(). I want to be able to get the Latitude and longitude from the city_data and display it in my html page. The problem i seem to be arriving at is that I am not able to call any of the information that is saved in the user session model. The information is there when i look at the admin as well as when i print out the querysets In the models i create a new session with usersession/usersessionmanager and and save that session as with the receiver Models.py from django.conf import settings from django.db import models from .signals import user_logged_in from .utils import get_client_city_data, get_client_ip class UserSessionManager(models.Manager): def create_new(self, user, session_key=None, ip_address=None, city_data=None, latitude=None, longitude=None): session_new = self.model() session_new.user = user session_new.session_key = session_key if ip_address is not None: session_new.ip_address = ip_address if city_data: session_new.city_data = city_data try: city = city_data['city'] except: city = None session_new.city = city try: country = city_data['country_name'] except: country = None try: latitude= city_data['latitude'] except: latitude = None try: longitude= city_data['longitude'] except: longitude = None session_new.country = country session_new.latitude = latitude session_new.longitude = longitude session_new.save() return session_new return … -
Rest api in django POST method
views.py from django.shortcuts import render, HttpResponse, get_object_or_404 from django.http import JsonResponse from .models import Locker from .serializers import LockerSerializer from rest_framework.response import Response from rest_framework import status from rest_framework.views import APIView from django.core import serializers def locker_data_response(request): if request.method == 'GET': locker_mac_address = request.GET.get('locker_mac_address') # this will return None if not found locker_information = get_object_or_404(Locker, locker_mac_address = locker_mac_address) print(locker_information) locker_information_serialize = LockerSerializer(locker_information) print(locker_information_serialize) return JsonResponse(locker_information_serialize.data) elif request.method == 'POST': locker_all_information_in_json = serializers.get_deserializer(request.POST()) print(locker_all_information_in_json) json data { "id": 1, "locker_name": "H15_c6d730", "locker_mac_address": "CE:B2:FE:30:D7:C6", "locker_rssi": -78, "locker_protocol_type": "5", "locker_protocol_version": "3", "locker_scene": "2", "locker_group_id": "0", "locker_org_id": "0", "locker_type": 5, "locker_is_touch": true, "locker_is_setting_mode": false, "locker_is_wrist_band": false, "locker_is_unlock": false, "locker_tx_power_level": "-65", "locker_battery_capacity": "57", "locker_date": 1518500996721, "locker_device": "CE:B2:FE:30:D7:C6", "locker_scan_record": "terterwer" } I am trying to send the json in this format from mobile device to my server.I check the get method, it works perfectly. But how can i post this json in my server and how can i get the json data in my server side? -
Multi select input in admin site
I am trying to create a form in Admin site that uses two fields from two different tables as input (single select & multi-select) and make it available for admin user selection and write this to another table. Following is my code. models.py class Employee(models.Model): id = models.IntegerField(primary_key=True, verbose_name='Employee Code') name = models.CharField(max_length=200, verbose_name='Employee Name') def __str__(self): return self.name class Product(models.Model): STATUS = (('New', 'New'), ('Go', 'Go'), ('Hold', 'Hold'), ('Stop', 'Stop')) code = models.IntegerField(primary_key=True, max_length=3, verbose_name='Product Code') name = models.CharField(max_length=100, verbose_name='Product Name') def __str__(self): return self.name class JobQueue(models.Model): emp_name = models.CharField(max_length=200, default='1001') product_code = models.CharField(max_length=200, default='100') admin.py: class JobQueueAdmin(admin.ModelAdmin): form = JobQueueForm fieldsets = ( (None,{'fields': ('emp_name', 'product_code'),}),) def save_model(self, request, obj, form, change): super(JobQueueAdmin, self).save_model(request, obj, form, change) forms.py: class JobQueueForm(forms.ModelForm): emp_name = forms.ModelChoiceField(queryset=Employee.objects.all(), widget=forms.ChoiceField()) product_code = forms.MultiValueField(queryset=Product.objects.all(), widget=forms.CheckboxSelectMultiple(), required=False) def save(self, commit=True): return super(JobQueueForm, self).save(commit = commit) class Meta: model = JobQueue fields = ('emp_name', 'product_code') When I start the web-server, I get the following error: AttributeError: 'ModelChoiceField' object has no attribute 'to_field_name' Can someone please shed some light on how do I get this form right? -
Django-allauth How to Ban Certain Users?
I'm using django-allauth for my Django web app. How can I ban certain users from logging in or restrict certain actions after they log in for a period of time? Should I just deactivate their accounts outright? What are some good solutions? -
Using Google/G-Suite as a user backend for django?
I'm looking at building a django app specifically designed for G-Suite domains. It requires users to be logged in to G-Suite, and would get permissions from groups in G-Suite. I know I could achieve this using django-allauth or similar, but that would involve the django app duplicating the user information in it's own database. In the interests of preventing unnecessary replication, is it feasible to have django directly use Google APIs to handle user logins, but still program the rest of the app in a django kind of a way? Are there any libraries that implement this? If not in django, are there other (python) frameworks that can do this? -
Create WiFi Hotspot project
I am a self-thought python programmer(amateur) and I would like to design a wifi hotspot program which would help to sell my wifi access on time period bases. If possible can someone please direct me where to get all the technical information on how I can go about it.