Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass input value to function in view.py
Objective: ** To pass input value itemnumbervalue to itemnumber() in views.py > Error occured: method object is not subscribable line 17 in view.py views.py: from .forms import InputForm def home_view(request): context1 ={} context1['form'] = InputForm(request.POST) return render(request, "input.html", context1) def itemnumber(request): *if (request.POST('submitted')): c = request.POST['ENTER_ITEM_NUMBER'] print("input valuegiven by user",c)* cursor = connection.cursor() try: itemnumbervalue = c C=cursor.execute(f"EXEC ValidateBusinessrule '0000000000{itemnumbervalue}'") result_set = cursor.fetchall() result_set1= [' {} '.format(x) for x in result_set] context = {"row": result_set1} return render(request, "home.html", context) finally: cursor.close() forms.py class InputForm(forms.Form): regex = re.compile('^([1-9]{8})$', re.UNICODE) ENTER_ITEM_NUMBER= forms.RegexField(max_length=8, regex=regex,help_text=("Required 8 digits between {0-9}.")) home.html <body> <table> <tr> <ul> <th>(column 1,column 2)</th> </ul> <tr> <ul > {% for row in row %} <td style= "text-align: center;"> {{ row }} </td> </ul> </tr> {% endfor %} </tr> </table> </body> input.html <body> <form action = "{% url 'item'%}" method = "POST"> {% csrf_token %} {{form}} <input type="submit" value=Submit" name="submitted"> </form> </body> problem details: To get input from user and give this input to itemnumbervalue in itemnumber() in view.py. I already validated by putting itemnumbervalue='12345678' (without input value from user) is working fine and getting resultant table. -
Django cannot assign variable to objects
when i'm trying to add data to uer in many to many as showen in views code below views.py def playList(request, name, language): playlist = { 'classic': Classic, } playlist2 = { 'classic': 'classic', } num = { 'ar': 1, 'en': 2, } if request.method == 'POST': form2 = FavoriteForm(request.POST) if form2.is_valid(): x = Profile.objects.get(user=request.user) x.playlist2[name].add(playlist[name].objects.get(id=request.POST.get(playlist2[name]))) form = playlist[name].objects.filter(lang=num[language]) context = {} for i in form: context[i] = i context = { 'form': form, 'playlist': playlist2[name], } return render(request, 'playlist.html', context) get this error that str object has no attr objects 'str' object has no attribute 'objects' when i'm change str to istance as showen in views code below views.py def playList(request, name, language): playlist = { 'classic': Classic, } playlist2 = { 'classic': Profile.classic, } num = { 'ar': 1, 'en': 2, } if request.method == 'POST': form2 = FavoriteForm(request.POST) if form2.is_valid(): x = Profile.objects.get(user=request.user) x.playlist2[name].add(playlist[name].objects.get(id=request.POST.get(playlist2[name]))) form = playlist[name].objects.filter(lang=num[language]) context = {} for i in form: context[i] = i context = { 'form': form, 'playlist': playlist2[name], } return render(request, 'playlist.html', context) i get this error that profile has no attr playlist2 'Profile' object has no attribute 'playlist2' and this is my model code modles.py class Classic(models.Model): name = models.CharField(max_length=50, … -
is there memory issue?
https://www.google.com/search?q=MemoryError+at+%2Fquery%2F+No+exception+message+supplied+Request+Method%3A+POST+Request+URL%3A+http%3A%2F%2F127.0.0.1%3A8000%2Fquery%2F+Django+Version%3A+2.2.5+Exception+Type%3A+MemoryError+Exception+Location%3A+ops.pyx+in+thinc.neural.ops.NumpyOps.allocate%2C+line+491+Python+Executable%3A+C%3A%5CUsers%5CTOSHIBA%5CAnaconda3%5Cpython.exe+Python+Version%3A+3.7.3+Python+Path%3A+%5B%27C%3A%5C%5CUsers%5C%5CTOSHIBA%5C%5CDocuments%5C%5Cclinical%5C%5Cdemoproject%27%2C+%27C%3A%5C%5CUsers%5C%5CTOSHIBA%5C%5CAnaconda3%5C%5Cpython37.zip%27%2C+%27C%3A%5C%5CUsers%5C%5CTOSHIBA%5C%5CAnaconda3%5C%5CDLLs%27%2C+%27C%3A%5C%5CUsers%5C%5CTOSHIBA%5C%5CAnaconda3%5C%5Clib%27%2C+%27C%3A%5C%5CUsers%5C%5CTOSHIBA%5C%5CAnaconda3%27%2C+%27C%3A%5C%5CUsers%5C%5CTOSHIBA%5C%5CAnaconda3%5C%5Clib%5C%5Csite-packages%27%2C+%27C%3A%5C%5CUsers%5C%5CTOSHIBA%5C%5CAnaconda3%5C%5Clib%5C%5Csite-packages%5C%5Cwin32%27%2C+%27C%3A%5C%5CUsers%5C%5CTOSHIBA%5C%5CAnaconda3%5C%5Clib%5C%5Csite-packages%5C%5Cwin32%5C%5Clib%27%2C+%27C%3A%5C%5CUsers%5C%5CTOSHIBA%5C%5CAnaconda3%5C%5Clib%5C%5Csite-packages%5C%5CPythonwin%27%5D+Server+time%3A+Mon%2C+23+Mar+2020+17%3A41%3A09+%2B0000&oq=me&aqs=chrome.1.69i59l2j0j69i57j69i61l3j69i60.2878j0j7&sourceid=chrome&ie=UTF-8 i received many times this error please help me -
How to pass input value to function in view.py
Objective: ** To pass input value itemnumbervalue to itemnumber() in views.py > Error occured: The view item.views.itemnumer didn't return a return a HTTP return response. It return none instead views.py: from .forms import InputForm def home_view(request): context1 ={} context1['form'] = InputForm(request.POST) return render(request, "input.html", context1) def itemnumber(request): *if (request.GET.get('submitted')): c = request.get['ENTER_ITEM_NUMBER'] print("input valuegiven by user",c)* cursor = connection.cursor() try: itemnumbervalue = c C=cursor.execute(f"EXEC ValidateBusinessrule '0000000000{itemnumbervalue}'") result_set = cursor.fetchall() result_set1= [' {} '.format(x) for x in result_set] context = {"row": result_set1} return render(request, "home.html", context) finally: cursor.close() forms.py class InputForm(forms.Form): regex = re.compile('^([1-9]{8})$', re.UNICODE) ENTER_ITEM_NUMBER= forms.RegexField(max_length=8, regex=regex,help_text=("Required 8 digits between {0-9}.")) home.html <body> <table> <tr> <ul> <th>(column 1,column 2)</th> </ul> <tr> <ul > {% for row in row %} <td style= "text-align: center;"> {{ row }} </td> </ul> </tr> {% endfor %} </tr> </table> </body> input.html <body> <form action = "{% url 'item'%}" method = "post"> {% csrf_token %} {{form}} <input type="submit" value=Submit" name="submitted"> </form> </body> problem details: To get input from user and give this input to itemnumbervalue in itemnumber() in view.py. I already validated by putting itemnumbervalue='12345678' (without input value from user) is working fine and getting resultant table. -
Error with inlined profile form save in django admin
I really confised, because problem sounds trivial, but I didn't googled anything related to this. I found one very simular question Django Admin Create Form Inline OneToOne but in my case I cannot remove signal, it'll break normal way of user creation in my app. I have model User and Profile connected OneToOne relationship (models.py): from django.db import models from django.contrib.auth.models import AbstractUser from django.db.models.signals import post_save, pre_save from django.dispatch import receiver from .managers import UserManager class User(AbstractUser): """auth/login-related fields""" username = None email = models.EmailField(unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email class Profile(models.Model): """profile fields""" user = models.OneToOneField(User, on_delete=models.CASCADE) about = models.CharField(max_length=2000, blank=True) telegram = models.CharField(max_length=25, blank=True) def save(self, *args, **kwargs): print('save profile', args, kwargs) # from admin it run 2 times, second with empty args, kwargs so PROBLEM HERE!!! super().save(*args, **kwargs) print('save profile complete') """receivers to add a Profile for newly created users""" @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): print('create_user_profile', created, instance.id) if created: try: p = Profile.objects.create(user = instance) print('succsecc!!!!', p, p.id) ## here profile object created and got id except Exception as e: print('create profile error', e) # never prints else: instance.profile.save() """ @receiver(post_save, sender=User) def save_user_profile(sender, instance, … -
Django application error ,error H10 ,503 while pushing app on HEROKU
From a lot of time i m trying to deploy my Django website on heroku, but i am getting this error h10 and which is i think for service unavailable. Here are some ss of logs and procfile. procfile content: web: gunicorn pop.pop.wsgi logs: logs of app -
Send data to frontend with Django channels
I created a Django channels consumer that, once the connection is open, should establish a connection to an external service, retrieve some data from this service and send the data to my frontend. Here is what i tried: import json from channels.generic.websocket import WebsocketConsumer, AsyncConsumer, AsyncJsonWebsocketConsumer from binance.client import Client from binance.websockets import BinanceSocketManager import time import asyncio client = Client('', '') trades = client.get_recent_trades(symbol='BNBBTC') class EchoConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() await self.send_json('test') bm = BinanceSocketManager(client) bm.start_trade_socket('BNBBTC', self.process_message) bm.start() def process_message(self, message): JSON1 = json.dumps(message) JSON2 = json.loads(JSON1) #define variables Rate = JSON2['p'] Quantity = JSON2['q'] Symbol = JSON2['s'] Order = JSON2['m'] print(Rate) When the connection is opened, this code will start printing some market orders to my console as soon as there is one. Now, instead of printing them to my console, i would like to send them to my frontend. Can someone explain me how to do that? Here is my frontend: {% load staticfiles %} <html> <head> <title>Channels</title> </head> <body> <h1>Testing Django channels</h1> <script> // websocket scripts var loc = window.location var wsStart = 'ws://' + window.location.host + window.location.pathname var endpoint = wsStart + loc.host + loc.pathname var socket = new WebSocket(endpoint) if (loc.protocol == 'https:'){ … -
Is there a way to transfer images between Django Rest Framework and Flutter app?
I want to take a picture on an app in flutter using the phone's camera or gallery and send it (POST request) to a Django REST API along with some other information. When the Django REST API receives the image along with the other information, it should resize the image and then save it in a model like: class Animals(models.Model): animal_image = models.ImageField(blank = True, upload_to=getFileName) animal_name = models.CharField(max_length = 30) species = models.CharField(max_length = 30) And later, the flutter app should be able to do a GET request to the API in order to get the image along with other details in the model and display the image on a widget (in another screen of the app). Therefore, I want to know how to do the Django REST API (views code to handle the GET and POST request) and Flutter implementation (code for making the GET and POST requests with images to the Django server). Either code snippets, links to blog posts or documentation would be good. If this way is not possible, what are the alternate ways through which images can be exchanged between Django and Flutter? Please Help Cheers!!! -
Django using bulk_update to update all records
With 2.2 we now have the option to bulk update: https://docs.djangoproject.com/en/3.0/ref/models/querysets/#bulk-update I have a model with say millions of rows and I want to efficiently update all the records. I am trying to use bulk_update, but which means I still have to load all the model objects in the memory, modify the field one by one and then use bulk update: What I am doing: def migrate_event_ip_to_property(apps, schema_editor): Event = apps.get_model('app' 'Event') events = Event.objects.all() for event in events: if event.ip: event.properties["$ip"] = event.ip Event.objects.bulk_update(events, ['properties'], 10000) Since there are millions of records, can I avoid doing Event.objects.all() and load all objects into the memory even while using bulk_update? -
djang-bootstrap avoid label tag being added when calling `field|bootstrap`
How to avoid label tag being added when calling field|bootstrap. I have the below code filter.py import django_filters from .models import Issue class IssuesFilter(django_filters.FilterSet): summary = django_filters.CharFilter(label="Summary", lookup_expr="icontains") class Meta: model = Issue Views.py def index(request): issues = IssuesFilter(request.GET, queryset=Issue.objects.all()) context = { 'user': request.user, 'message': 'LogedIn', 'filter': issues } return render(request, 'testApp/index.html', context) index.html {% extends "firstPage/base.html" %} {% load bootstrap %} {% load render_table from django_tables2 %} {% load crispy_forms_tags %} {% block body %} <form method="GET"> <table> {% for field in filter.form %} <tr class="table table-borderless"> <td>{{ field.label_tag }}</td> <td>{{ field|bootstrap }}</td> </tr> {% endfor %} </table> <button type="submit" class="btn btn-primary">Search</button> </form> {% endblock %} When I add field|bootstrap I could see the label tag of the field is displayed. Is it possible to remove additional label tag from being added? -
How to filter useing look up method "in or range" and make sure if any of the item in the list is not available then returns empty queryset
My code snippet: filtered_queryset = Model.objects.filter( Q(model_one__status="OPEN") & Q(model_two__date__range=[start_date, end_date]) & Q(model_two__model_three__pk__in=model_three_id_list) & Q(model_two__something_to_sell__gte=F("model_two__already_sold") + requested_amount) ) In the above snippet I want the following line to work such a way that if some date is missing then it should not return others. What actually happens in range/in operator is that if it finds one or more matching data it returns those data in the queryset. But that's not what I need. I need to make sure that if all the date matches then only return the queryset otherwise it should be empty. Q(model_two__date__range=[start_date, end_date]) We can also use "in" operator if the solution for in operator is possible. In this case code snippet will be: Q(model_two__date__in=date_list) -
Django: implement multiple user levels / roles / types
I have been using Django for quite a while but never have I thought of this until now. Currently, I have a project that contains different user levels. Usually, in my past experience, I only developed systems using Django with only two user levels which are superuser and normal/regular user. So my question is what are the effective ways to present these different user levels in the model/database? Here, I'm going to use a school system as an example and also provide some of my initial thoughts on implementing it. User levels: Admin (superuser & staff) Principle Teacher Students Method #1: Add new tables based on each user level from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): user = models.CharfieldField(max_length = 10, unique = True) class Admin(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) class Priciple(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) Method #2: Add additional user types attributes in the User model from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): user = models.CharfieldField(max_length = 10, unique = True) is_superuser = models.BooleanField(default = False) is_staff = models.BooleanField(default = False) is_principle = models.BooleanField(default = False) is_teacher … -
Django Many to Many Varible errot
when i add to user from many to many relation with this code Profile.objects.get(user=request.user).sad.add(Sad.objects.get(id=15)) it add but when i replace them with variable like this Profile.objects.get(user=request.user).playlist2[name].add(playlist3[name].objects.get(id=request.POST.get(playlist2[name]))) and i print varibale and it return with same sad Sad 15 get this error -
Django deletes table data on its own
iam using Django rest framework , react.js for the frontend and postgresql...the problem which i think its weird django deletes product table data on its own after a while i dont know why ...iam using django since a year and i have never seen this before. this is my model class products(models.Model): name=models.CharField(max_length=50) Barcode=models.CharField(max_length=50) category=models.ForeignKey(category,on_delete=models.CASCADE) description=models.TextField() quantity=models.IntegerField(default=100) price=models.FloatField(default=100.0) image=models.ImageField(upload_to='pics',default='') cost=models.FloatField(default=100.0) branch=models.ForeignKey(branch,on_delete=models.CASCADE) def __str__(self): return self.name -
Django installation issues
i configured django and apache on an ec2 server with a connection to a remote rds server. which is working fine. i can access the ec2 server and the database (via ssh to the ec2 server and then to the rds server) i tried to run a migration with sudo python manage.py and it worked. the database shows my tables. i use virtual environment with the python mod_wsgi installed which is loaded in the apache2.conf and in the 000-default.conf i have the wsgi daemon process, and script references. when i try to run the application through my browser i get a 500 internal server error with the following error message: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? mod_wsgi (pid=7875): Target WSGI script '/var/www/wuyeguanli/wuyeapp/wuyeapp/wsgi.py' does not contain WSGI application 'application'. the complete error message -
Django - accessing related objects in a template
How can I access a related object in a django template? I simply want to display the post title of the the bookmark at my template. Assuming the following view and model(s): def my_bookmarks(request): if request.method == 'GET': list_my_bookmarks = sorted( chain( UserBookmarks.objects.filter(user=request.user), ), key=attrgetter('date_added'), reverse=True ) paginator = Paginator(list_my_bookmarks, 20) # Show 20 bookmarks per page page = request.GET.get('page') my_bookmarks = paginator.get_page(page) user = request.user args = {'user': user, 'my_bookmarks': my_bookmarks, } return render(request, 'App/my_bookmarks.html', args) bookmarkable_post_models = models.Q(app_label='App', model='post') | models.Q(app_label='App', model='model-b') | models.Q(app_label='App', model='model-c') class UserBookmarks(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(User, on_delete=models.CASCADE, null=False, blank=False) content_type = models.ForeignKey(ContentType, limit_choices_to=bookmarkable_post_models, related_name='bookmarks', related_query_name='bookmark', on_delete=models.CASCADE, null=True, blank=False) object_id = models.CharField(max_length=50, blank=False) content_object = GenericForeignKey('content_type', 'object_id') date_added = models.DateTimeField(auto_now_add=True, blank=False) class Post(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(verbose_name="Post Title", max_length=20) content = models.TextField(verbose_name="Content of Post") ... bookmarks = GenericRelation(UserBookmarks, related_query_name='post') Accessing the bookmark objects itself does not seem to be a problem if I do: {{ my_bookmarks }} at my template but i dont understand how to access the post element behind the bookmark Thanks for reading -
issue in setting up tornado.web.Application
In tornado (python) instead of creating an instance of tornado.web.Application(), I tried to make changes in the class while calling it using init. import tornado.web import tornado.httpserver import tornado.ioloop import tornado.options import os.path from tornado.options import define, options define("port", default=8000, help="run on the given port", type=int) class MainHandler(tornado.web.RequestHandler): def get(self): self.render("index.html", page_title="My Bookstore | HOME", header_text="Welcome to My Bookstore!") class Application(tornado.web.Application): def __init__(self): handlers = [ (r'/', MainHandler), ] settings = dict( template_path = os.path.join(os.path.dirname(__file__), "templates"), static_path = os.path.join(os.path.dirname(__file__), "static"), debug = True ) tornado.web.Application(self, handlers, **settings) if __name__ == "__main__": tornado.options.parse_command_line() #Note: not creating an instance of application here ('app'), just creating a list of handlers and a dict of settings and passing it to the superclass. http_server = tornado.httpserver.HTTPServer(Application()) http_server.listen(options.port) tornado.ioloop.IOLoop.instance().start() But I'm getting this error, Traceback (most recent call last): File "main.py", line 44, in <module> http_server = tornado.httpserver.HTTPServer(Application()) File "main.py", line 27, in __init__ tornado.web.Application(self, handlers, **settings) File "C:\Python\Python37\lib\site-packages\tornado\web.py", line 2065, in __init__ handlers = list(handlers or []) TypeError: 'Application' object is not iterable What is the error, and how can I solve it? -
Dramatiq: Attempted relative import with no known parent package
Using Django framework with Dramatiq for multithreading. Currently when trying to initiate a worker I receive the following error. I have no issue compiling this import through the initial boot of the server. Is there anything I'm missing in the below code? Lower Half of Error [2020-04-05 18:28:24,920] [PID 5520] [MainThread] [dramatiq.WorkerProcess(0)] [ERROR] Failed to import module. Traceback (most recent call last): File "c:\program files\python38\lib\site-packages\dramatiq\cli.py", line 330, in worker_process module, broker = import_broker(args.broker) File "c:\program files\python38\lib\site-packages\dramatiq\cli.py", line 120, in import_broker module, broker = import_object(value) File "c:\program files\python38\lib\site-packages\dramatiq\cli.py", line 109, in import_object module = importlib.import_module(modname) File "c:\program files\python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File ".\splitter.py", line 10, in <module> from .models import Highlight, Testdata, Video ImportError: attempted relative import with no known parent package from splitter.py - the … -
conditional editing in django model
I am trying to find a way to update fields values automatically like when a user update the Type Action, Status and finish time fields get updated also.for example: if Type == 'On store' Action == 'Requested' and Status == 'Pending' and Time_Finished == Today the model goes like this class order(models.Model): Time_Registered = models.DateField(blank=False) Number = models.CharField(max_length=500) Type = models.ForeignKey(Type, on_delete=models.CASCADE) Action = models.CharField(max_length=500, blank=True, null=True, choices=ACTION) Status = models.ForeignKey(Status, on_delete=models.CASCADE) Time_Finished = models.DateField(blank=False) -
How do I model a registration system with the following relationship constraints in Django?
I am trying to create a hackathon management system web application using Django. Each hackathon can have as many participating universities as possible (No constraints here).Now, each participating university can have at most 3 teams and each team can have at most 4 persons (1-4). I'm new to Django so help would be much appreciated. from django.db import models class Hackathon(models.Model): name = models.CharField(max_length=50,blank=True,default='') eventId = models.CharField(max_length=50, blank=True, default='') startDate = models.DateField(null=True) endDate = models.DateField(null=True) location = models.TextField(max_length=100, blank=True, default='') description = models.TextField(max_length=800, blank=True, default='') #participants = models.ManyToManyField(...)?? def __str__(self): return self.name class University(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Team(models.Model): team_name = models.CharField(max_length=50) member_count = models.PositiveIntegerField(default=1, validators=[MinValueValidator(1), MaxValueValidator(4)]) uni = models.ForeignKey(University, on_delete = models.CASCADE) def __str__(self): return self.team_name class Person(models.Model): name = models.CharField(max_length=50) belongs_to = models.ForeignKey(Team,on_delete = models.CASCADE) -
ConnectionError in Twilio Django
when i try to integrate with twilio service to verify a mobile number: client = twilio.rest.Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN) verification = client.verify \ .services(TWILIO_SERVICE_SID) \ .verifications \ .create(to='+'+country_code+phone, channel='sms') i get that error HTTPSConnectionPool(host='verify.twilio.com', port=443): Max retries exceeded with url: /v2/Services/V*****************/Verifications (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f4a3884f150>: Failed to establish a new connection: [Errno -2] Name or service not known',)) any help? -
Manager isn't available; 'auth.User' has been swapped for 'account.Account'
I get always the error AttributeError: Manager isn't available; 'auth.User' has been swapped for 'account.Account' When I go on http://127.0.0.1:8003/register everything works, when I press the "submit" button i get that error. I tried different solutions but still I can't understand the error. account/admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from account.models import Account class AccountAdmin(UserAdmin): list_display = ('email','username','date_joined', 'last_login', 'is_admin','is_staff') search_fields = ('email','username',) readonly_fields=('date_joined', 'last_login') filter_horizontal = () list_filter = () fieldsets = () admin.site.register(Account, AccountAdmin) account/forms.py from django import forms from django.contrib.auth.forms import UserCreationForm #CustomUserCreationForm from django.contrib.auth import authenticate from account.models import Account class RegistrationForm(UserCreationForm): email = forms.EmailField(max_length=254, help_text='Required. Add a valid email address.') class Meta: model = Account fields = ('email', 'username', 'password1', 'password2', ) account/models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager # Create your models here. class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have a username') user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", … -
django using cached database query problem
I have django application witch save traffic logs . the problem is when we refresh page doesnt show new logs its like query set cached some where. I made a manager to return last n log. this is my code from django.db.models import Manager class LogMannager(Manager): def _last(self,num,server=None,camera=None): if camera: return self.get_queryset().filter(camera=camera).order_by('-id')[:num] elif server: return self.get_queryset().filter(server=server).order_by('-id')[:num] else: ret = self.get_queryset().all().order_by('-id')[:num] print(ret) return ret the server is in production and using uwsgi -
how to access child model from parent model
I am trying to get data from child model through the parent model, I don't know if it possible or there is a way of doing it, I would be grateful for any solution models.py class Client_Data(models.Model): RC = models.CharField(max_length=50) Raison_social = models.CharField(max_length=254) NIF = models.CharField(max_length=50,unique=True) AI = models.CharField(max_length=50,unique=True) NIS = models.CharField(max_length=50,unique=True) Banque = models.CharField(max_length=50,unique=True) CB = models.CharField(max_length=50) adresse = models.CharField(max_length=50) slug = models.SlugField(blank=True, unique=True) active = models.BooleanField(default=True) class Contact(models.Model): client = models.ForeignKey(Client_Data,blank=True,on_delete=models.CASCADE) Nom = models.CharField(max_length=50) post = models.CharField(max_length=50) Tel = models.CharField(max_length=50) email = models.EmailField(max_length=255,unique=True) contact_type = models.CharField(default='Client_contact',max_length=50) views.py def client_update(request,slug): book = get_object_or_404(Client_Data, slug=slug) contact = Contact.objects.select_related().filter(client=book.id) print(contact) if request.method == 'POST': form = ClientForm(request.POST, instance=book) contact_form = Contact_Form(request.POST, instance=contact) else: form = ClientForm(instance=book) contact_form = Contact_Form(instance=contact) return save_client_form(request, form,contact_form ,'Client_Section/partial_client_update.html') -
TypeError: save() missing 1 required positional argument: 'self' in djjango
my code: from django.shortcuts import render,redirect from django.contrib.auth.models import User # Create your views here. def register(request): if request.method=='POST': first_name=request.POST['first_name'] last_name=request.POST['last_name'] username=request.POST['username'] password1=request.POST['password1'] password2=request.POST['password2'] email=request.POST['email'] if password1==password2: if User.objects.filter(username=username).exists(): print("usernmae taken") elif User.objects.filter(email=email).exists(): print("email taken") else: user=User.objects.create_user(username=username,password=password1,email=email,first_name=first_name,last_name=last_name) User.save(); print("user created") else: print("passwords not matching") return redirect('/') else: return render(request,'register.html') my console log: File "E:\coding\fyp\travel\accounts\views.py", line 21, in register User.save(); TypeError: save() missing 1 required positional argument: 'self' [05/Apr/2020 11:49:59] "POST /accounts/register HTTP/1.1" 500 69154 E:\coding\fyp\travel>python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). April 05, 2020 - 11:52:09 Django version 2.2.5, using settings 'travel.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. ignore lllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll