Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Object of type Logo is not JSON serializable
I'm trying to build django rest api which will get images from front part and also serve it via REST APi, the problem is that eventho I'm able to post data to django via PostMan, still I get error Object of type 'Logo' is not JSON serializable. Data is already in database but I would like to fix this issue but dont know where to start, tried to change Response to JsonResponse but it brought no effect Model class Logo(models.Model): name = models.CharField(max_length=60) preview = models.ImageField() thumb = models.ImageField() thumbL = models.ImageField() dataL = models.TextField(blank=False) thumbS = models.ImageField() dataS = models.TextField() posL = models.CharField(max_length=60) posS = models.CharField(max_length=60) def __str__(self): return str(self.name) Serialization: class LogoSerializer(serializers.ModelSerializer): posL = serializers.CharField(required=False) posS = serializers.CharField(required=False) dataL = serializers.CharField(required=False) dataS = serializers.CharField(required=False) class Meta: model = Logo fields = ('__all__') def create(self, validated_data): return Logo.objects.create(**validated_data) and View: class LogoViewSet(viewsets.ViewSet): parser_classes = (MultiPartParser, FormParser) def list(self, request, *args, **kwargs): queryset = Logo.objects.all() serializer = LogoSerializer(queryset, many=True) return Response(serializer.data) def post(self, request, *args, **kwargs): serializer = LogoSerializer(data=request.data) if serializer.is_valid(): serializer.validated_data['posL'] = positionL serializer.validated_data['posS'] = positionS bg = serializer.save() return Response(bg, status=status.HTTP_201_CREATED) else: bg = serializer.errors return Response(bg, status=status.HTTP_400_BAD_REQUEST) -
Django : How to differentiate post requests from different pages that is coming to the same page?
I have two pages both containing form. However both the pages are sending post request to the same page. How do I differentiate which page has sent the request. dummy.html(first page) <form action="/nda" method='POST'> {% csrf_token %} <button type="submit" name="submit" id="submit" value="I Agree" target="_blank">I Agree</button> <button onclick="window.open('/greeting')" target="_blank"> I Disagree </button></br> </form> This page redirects to nda page. nda.html(second page) This page also redirects to the same page. <form action="/nda"> {% csrf_token %} <button type="submit" name="submit" id="submit" value="I Agree" target="_self">I Agree</button> <button onclick="window.open('/greeting')" target="_self"> I Disagree </button></br> </form> My question is, how do I differentiate in my view that from which page it was coming from the page dummy or the same page that was nda. views.py def nda(request): if request.method=='POST' : # if this is from dummy I want to do this return render(request,'mainapp/nda.html',{'user':email.split('@')[0]}) if request.method=='POST' : # if this is from same page that is nda I want to do this return render(request,'mainapp/home.html') I am unable to figure out, how do I handle both cases differently -
Django REST Framework ObtainAuthToken User Login Api view
Hello Django community, I want to send back the email and the id of the user alongside the token when the user authenticate. I guess I must change the UserLoginApiView class but I don't know how to override the ObtainAuthToken class to do that. Does anybody have suggestions it would be very helpful? class UserLoginApiView(ObtainAuthToken): """Handle creating user authentication tokens""" renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES This is my entire code on Github: https://github.com/KrestouferT/profiles-rest-api -
Is there a way to execute a big for-loop via Python Multiprocessing?
I am taking an excel file(.xlsx) as an input which has approx 30,000 rows. I am using XLRD to read the excel file. After reading the file i am doing some processing on the data and storing in an array of objects. The thing is that my code works fine for small number of rows like 100 to 200 but it gets stuck in a loop for the bigger file. I have tried using python Multithreading but never got a proper solution. def read(file_object, request): company_id = request.session[SessionKeys.COMPANY_KEY] wb = xlrd.open_workbook(file_object.file.path) data = dict() for sheet_index, sheet in enumerate(wb.sheets()): number_of_rows = sheet.nrows number_of_columns = sheet.ncols items = [] needs_edit = False for row in range(1, number_of_rows): al = AttendanceLog() for index, col in enumerate(range(number_of_columns)): al.company_id = company_id al.file_id = file_object.id if index not in [0, 1, 4, 6]: value = sheet.cell(row, col).value if index == 2: al.code = value try: al.employee = Employee.objects.filter(company_id=company_id).get(code=value) al.name = al.employee.name except ObjectDoesNotExist: needs_edit = True if index == 3: al.date = xlrd.xldate.xldate_as_datetime(value, wb.datemode).date() if index == 5: al.time = value items.append(al) data[sheet_index] = {'items': items, 'needs_edit': needs_edit} return data -
Django humanize intword remove number round
Currently i'm using intword in django to output the price field(bigint) like so : {{ property.price| intword }} But i have problem with the precision of the round function of intword For example if the data is 1490000000 then it should output 1.490 billion but instead it output 1.5 billion . Since this a price data i don't want that much rounding, is there a way to disable rounding or maybe only round till the third fourth number in the intword function from django. If there no options then i guess i have to go basic conversion diversion way. -
how to run a user input python matrix program in django? [duplicate]
This question already has an answer here: How to Run this python script with Django? 1 answer m = int(input('number of rows, m = ')) n = int(input('number of columns, n = ')) matrix = []; columns = [] for i in range(0,m): matrix += [0] for j in range (0,n): columns += [0] for i in range (0,m): matrix[i] = columns for i in range (0,m): for j in range (0,n): print ('entry in row: ',i+1,' column: ',j+1) matrix[i][j] = int(input()) print (matrix) -
Brand Filter by Category in shopping django rest
I am facing problems on filtering Brand by Category in Django Rest Framework. class Category(TimeStamp): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique=True, blank=True) icon = models.ImageField(upload_to='category_icons', null=True, blank=True) parent = models.ForeignKey('self', on_delete=models.SET_NULL, related_name='children', null=True, blank=True) class Brand(models.Model): brand_name = models.CharField(max_length=150) brand_image = models.ImageField(upload_to='brand_images', null=True, blank=True) category = models.ForeignKey(Category, on_delete=models.DO_NOTHING, null=True) here I have two models. For example I have a Category like Clothing -> Foot Wear -> Shoes if user enter Clothing category I should get all brands in Clothing but when I go to Shoes section I should get all brands in Shoes category. For this How can I write query_set? Any help would appreciated! Thanks in advance! -
celery worker crash when i start another
i use django with celery and redis. I would like to have three queues und three workers. My celery settings in the settings.py looks like this: CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE = 'Europe/Berlin' # CELERY QUEUES SETUP CELERY_DEFAULT_QUEUE = 'default' CELERY_DEFAULT_ROUTING_KEY = 'default' CELERY_TASK_QUEUES = ( Queue('default', Exchange('default'), routing_key='default'), Queue('manually_crawl', Exchange('manually_crawl'), routing_key='manually_crawl'), Queue('periodically_crawl', Exchange('periodically_crawl'), routing_key='periodically_crawl'), ) CELERY_ROUTES = { 'api.tasks.crawl_manually': {'queue': 'manually_crawl', 'routing_key': 'manually_crawl',}, 'api.tasks.crawl_periodically': {'queue': 'periodically_crawl', 'routing_key': 'periodically_crawl',}, 'api.tasks.crawl_firsttime': {'queue': 'default', 'routing_key': 'default',}, } Later i will start the workers with celery multi, but in the development phase i would like to start the worker manually to see errors or so. I start the redis server with redis-server and than i start the first worker default with: celery -A proj worker -Q default -l debug -n default_worker If i try to start the next worker in a new terminal with: celery -A proj worker -Q manually_crawl -l debug -n manually_crawl I get an error in the first default worker terminal: [2019-10-28 09:32:58,284: INFO/MainProcess] sync with celery@manually_crawl [2019-10-28 09:32:58,290: ERROR/MainProcess] Control command error: OperationalError("\nCannot route message for exchange 'reply.celery.pidbox': Table empty or key no longer exists.\nProbably the key ('_kombu.binding.reply.celery.pidbox') … -
Python Django Admin create new object and filter horizontal Filter elements
I would like to create a custom horizontal filter inside Django admin. My use case looks like this. I am working on a Testmanagment tool. You got "Projects" like websiteA or WebsiteB. Every Project has its own Elements/Groups. E.g WebsiteA got "Dashboard" and "Login" and WebsiteB has "Users" and "Orders". If I am creating a new Testcase I would like to choose the Project first and offer a filtered list to all corresponding Elements for that project. I don't want to get all Elements/Groups for a new Testcase. My code looks something like this: Forms.py: class TestCaseForm(forms.ModelForm): @staticmethod def groupSmartFilter(): return GroupModel.objects.filter(id=2) #working fine so far but should be something like return Projects.objects.filter(projectname=<$project_from_dropdown>).groups() def __init__(self, *args, **kwargs): forms.ModelForm.__init__(self, *args, **kwargs) self.fields['groups'].queryset = TestCaseForm.groupSmartFilter() class Meta: model = TestCaseModel fields = ('name', 'TestcaseNummer', 'project','groups', 'description' , 'url' ) admin.py class TestCaseAdmin(CompareVersionAdmin): form = TestCaseForm filter_horizontal = ('groups',) -
Django Paginator influences select_related()
I have a query that makes a selection from tables. The result of the selection changes if I connect a paginator.As a result, lines with Paginator appear, which should not be. The code will be below: views.py def payments(request): paymentsss = Transaction.objects.select_related('currency', 'payment_source__payment_type')[:2700] paginator = Paginator(paymentsss, 25) page = request.GET.get('page') payments = paginator.get_page(page) return render(request, "payments.html", {'payments': payments}) HTML code: <tbody> {% for payment in payments %} <tr role="row" class="odd"> <td>{{ payment.id }}</td> <td>{{ payment.payment_source.payment_type.name}}</td> <td>{{ payment.currency.iso_name }}</td> </tr> {% endfor %} </tbody> <div class="pagination"> <span class="step-links"> {% if payments.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ payments.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ payments.number }} of {{ payments.paginator.num_pages }}. </span> {% if payments.has_next %} <a href="?page={{ payments.next_page_number }}">next</a> <a href="?page={{ payments.paginator.num_pages }}">last &raquo;</a> {% endif %} </span> What could be the problem ? -
My data is generated dynamically using django pass through view.py but how can I select those element in HTML using jquery or javascript?
My data is generated dynamically using Django pass through view.py but how can I select those element in HTML using jquery or javascript? because all my element will have the same class and id -
Djagno-REST-framework-datatables didn't show anything
I'm trying to practice Django with REST api, but when I try to run nothing happened. It still show the processing sign. Here is my reference:https://github.com/izimobil/django-rest-framework-datatables I try different version of jquery but seems it is not a solutions. Here is my code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0/css/bootstrap.css"> <link rel="stylesheet" href="//cdn.datatables.net/1.10.16/css/dataTables.bootstrap4.min.css"> </head> <body> <div class="row"> <div class="col-sm-12 text-center"> <h4 class="bg-primary text-white p-2" style="margin: 15px;">Full example with foreign key and many to many relation</h4> <div class="btn-group btn-group-toggle" role="group" aria-label="Decades"> <button class="btn btn-success btn-decade">All time</button> </div> </div> </div> <div class="row"> <div class="col-sm-12"> <table id="datatables" class="table table-striped table-bordered" style="width:100%"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Link</th> <th>Context</th> <th>Time</th> <th>Action</th> </tr> </thead> </table> </div> </div> <script src="//code.jquery.com/jquery-1.12.4.js"></script> <script src="//cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script> <script src="//cdn.datatables.net/1.10.16/js/dataTables.bootstrap4.min.js"></script> <script type="text/javascript"> $(document).ready(function() { var table = $('#datatables').DataTable({ "processing": true, "serverSide": true, "ajax": { "url":"/newsapi/?format=datatables", "type": "GET" }, "columns": [ {"data": "id"}, {"data": "name"}, {"data": "link"}, {"data": "context"}, {"data": "created_time"}, { "data": null, "defaultContent": '<button type="button" class="btn btn-info">Edit</button>' } ] }); }); </script> </body> </html> Serializers.py: from rest_framework import serializers from stock.models import Stock class StockSerializer(serializers.ModelSerializer): class Meta: model = Stock fields = '__all__' Views.py class Get_news_List(APIView): def get(self, request): stock = Stock.objects.all() serialized = StockSerializer(stock, many=True) return Response(serialized.data) -
python django: pre-select dropdown of custom field
I am newbie to django python. I am trying to create CRUD using custom fields. Un update page, It shows foriegn key value instead of dropdown. Here is my code Model.py: class RoleModel(models.Model): rol_id = models.AutoField(primary_key=True) rol_name = models.CharField(max_length=255) class Meta: db_table = "tbl_roles" def __str__(self): return self.rol_name class UserModel(models.Model): usr_id = models.AutoField(primary_key=True) user_rolidfk = models.ForeignKey(RoleModel, blank=True, null=True, db_constraint=True, on_delete=models.CASCADE) usr_name = models.CharField(max_length=255) usr_email = models.EmailField() usr_picture = models.FileField() usr_aboutme = models.TextField() usr_datetime = models.DateTimeField(auto_now_add=True) class Meta: db_table = "tbl_users" def __str__(self): return str(self.user_rolidfk) + ' - ' + ', '.join([rol.rol_id for rol in self.user_rolidfk.all()]) def __unicode__(self): return self.usr_name forms.py: class RoleForm(forms.ModelForm): class Meta: model = RoleModel fields = "__all__" class UserForm(forms.ModelForm): class Meta: model = UserModel fields = ['usr_name', 'user_rolidfk'] Views.py: def useredit(request, id): users = UserModel.objects.get(usr_id=id) roles = RoleModel.objects.all() form = UserForm() data = {"users": users, "roles": roles, "form": form } return render(request,'user_edit.html', data) user_edit.html: {{ users.user_rolidfk }} {{ form.user_rolidfk }} -
Django ORM for SQL SELECT query
cursor.execute("SELECT id FROM student where name=%s", [s[2]]) student_id = cursor.fetchone() I have s[2] value as 'Jack' I am trying to convert this into Django ORM, but getting empty queryset. Could you please help me with this. My ORM for above query is as below: student_id = Student.objects.filter(name=s[2]).values_list('id') While printing the student_id I am getting empty queryset. <QuerySet []> I need to get the id of the student present on s[2] which in this case is 'Jack'. Thank you, -
Is there a way on Serializer perform create to save a field which is a Foreign Key
I have two models Timesheet and Employee now on my use case I want to save automatically the employee field of the timesheet using the perform_create but the api returns an error of "ValueError at /api/timesheet_entry/\nCannot assign \", , ]>\": \"Timesheet.employee\" must be a \"Employee\" instance. What I was trying to do is save the Timesheet's employee field to the Employee's login field using the id. below are the information on the models, serializer and the viewsets. class Timesheet(models.Model): start_date = models.DateTimeField(verbose_name="Start Date", null=True, blank=True, default=None, editable=True, help_text="", unique=False, db_index=False,) end_date = models.DateTimeField(verbose_name="End Date", null=True, blank=True, default=None, editable=True, help_text="", unique=False, db_index=False,) employee = models.ForeignKey('Employee', on_delete=models.PROTECT, related_name="timesheet_entry_employee", verbose_name="Employee", null=True, blank=True, editable=True, unique=False) comment = models.CharField(verbose_name="Comment", null=True, blank=True, default=None, editable=True, max_length=255,) total_hours = models.DecimalField(verbose_name="Total Hours", null=True, blank=True, default=0.00, max_digits=19, decimal_places=2,) and class Employee(models.Model): name = models.CharField(verbose_name="Name", max_length=255,) login = models.ForeignKey(User, on_delete=models.PROTECT, related_name="employee_login", verbose_name="Login", editable=True) hourly_cost = models.DecimalField(verbose_name="Hourly Cost", null=False, blank=False, editable=True, max_digits=19, decimal_places=2,) charge_out_rate = models.DecimalField(verbose_name="Charge Out Rate", null=False, blank=False, max_digits=19, decimal_places=2,) and in the serializer class TimesheetEntrySerializer(WritableNestedModelSerializer): employee = PrimaryKeyRelatedField(many=False, read_only=False, allow_null=True, queryset=models.Employee.objects.all()) viewset's perform create def perform_create(self, serializer): request = self.request.user.id employee_user = Employee.objects.filter(employee__login__id=request) return serializer.save(employee=employee_user) -
Translations in Django 2.2 is not working
I'm working on a project using Python(3.7) and Django(2.2) in which I have to make the site available in 2 languages (English and Chinese). I have searched a lot and tried every possible solution but no success. Here's what I have tried: Install gettext on my system and link it Add the following setting in settings.py: Add middleware 'django.middleware.locale.LocaleMiddleware', after Session and before Common, then add USE_I18N = True & USE_L10N = True, after that mentioned the languages as: LANGUAGES = ( ('en', _('English')), ('zh-hans', _('简体中文')), ) then add locale path as: LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) Then run the command as: django-admin makemessages -all it creates the directory as: └── zh_hans └── LC_MESSAGES └── django.po After that, I add the translations in django.po and ran the command as django-admin compilemessage which generate the file django.mo I added a url for i18n as: re_path(r'^i18n/', include('django.conf.urls.i18)) and below is my template which is loading by render from view as: {% load i18n %} <form action="{% url 'set_language' %}" method="post"> {% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"/> <select name="language"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% for lang in LANGUAGES %} <option value="{{ lang.0 }}" … -
Django clean method of model doesn't gets called when saving the data
So I having this model where I am storing the information that my entity is sending . class NewProvisionalEmployeeMail(models.Model): offer_id = models.AutoField(primary_key=True) email = models.EmailField(max_length=70, null=False, blank=False, unique=False) token = models.TextField(blank=False, null=False) offer_sent_by = models.CharField(max_length=50) position_assigned = models.CharField(max_length=50, null=False, blank=False, default="Developer") def __str__(self): return str(self.offer_sent_by) +" to " + str(self.email) def clean(self): if(NewProvisionalEmployeeMail.objects.filter(email=str(self.email)).exists()): NewProvisionalEmployeeMail.objects.filter(email=str(self.email)).delete() What was expected : Before saving data to this model, I expect the clean method to be called automatically. I have tried this with my other models over there it was working but its not working over here. This is the part where I am saving the data. def sendoffer(request): context = {} hostname = request.get_host() + "/dummyoffer" if request.method=='POST': email = request.POST.get('email') position = request.POST.get('opt') context['success_message'] = "Mail has been sent!!!" token = get_secret_key(email) msg=EmailMultiAlternatives('ATG',"Hello\n we are from atg.dev.party\n Click on this link to get offer","jecrccanteen@gmail.com",[email]) message = "http://" + hostname + "/" + token msg.attach_alternative(message,"text/html") msg.send() newusermail = NewProvisionalEmployeeMail(email=email, token=token, offer_sent_by=request.user.username, position_assigned=position) newusermail.save() return render(request, 'mainapp/offer.html',context) newusermail.save() is the part where the data is going to be saved and before that I expect clean method to be called which checks for email if it already exists in our database and if it does we … -
Multiple emails configurations to send emails (if admin have multiple emails then admin need to choose )in Django using python
sending an email from one email is working fine, but if we want send an email to user from multiple emails(i have 3 emails from that i need to choose any one and receiver get email whichever i chose ) so please help me I'm new to Django and Python -
Django - Displaying model data on Elasticsearch search result
I am making a booking website, and I have implemented elasticsearch. I got the search working just fine, but now I am kind of stuck on a problem. What I'm trying to do is display the lowest price for the apartment the user has searched for, in the search results. The prices are stored in the "ApartmentPrices" model : class ApartmentPrices(models.Model): apartment = models.ForeignKey(Apartment, on_delete="models.CASCADE", related_name="price") price_start_date = models.DateField(blank=True, null=True) price_end_date = models.DateField(blank=True, null=True) price = models.IntegerField() def __str__(self): return self.apartment.title This is my document and view for the actual search : search view : def search(request): apartments = Apartment.objects.all() q = request.GET.get('q') if q: apartments = ApartmentDocument.search().query("match", title=q) else: apartments = '' return render(request, 'search/search_elastic.html', {'apartments': apartments, "q": q, }) elasticsearch document: apartments = Index('apartments') @apartments.document class ApartmentDocument(Document): class Django: model = Apartment fields = [ 'title', 'id', 'bedrooms', 'list_date', ] I have tried passing in apartment_id to the search view, but I cannot get it to work. Can anyone point me in the right direction please ? How do I access model data from a ES query ? Thank you ! -
Sending input names in Django form having javascript code
I have the following code: <form id="buttonForm" action = "/goSomeWhere" method="post" > <input type="submit" name="bnext" value="Next Page" > <input type="submit" name="bprevious" value="Previous Page" > </form> When either one of this two buttons are submitted I receive "bnext" or "bprevious" values in Django View request.POST so I can further construct the logic that I need. But when I'm trying to insert some javascript for the second button I loose those values: <input type="submit" name="bnext" value="Next Page" > <input type="submit" name="bprevious" id="bpid" onclick="disable()" value="Previous Page" > function disable() { document.getElementById("bpid").disabled = true; document.getElementById("buttonForm").submit(); } There is a way to do this and still receiving input names values ? -
django-oscar error MTPRecipientsRefused at /checkout/preview/ How to fix it
hi what happen with SMTPRecipientsRefused at /checkout/preview/ anyidea ??? django-oscar Environment: File "/usr/lib/python3.6/smtplib.py" in sendmail 881. raise SMTPRecipientsRefused(senderrs) Exception Type: SMTPRecipientsRefused at /checkout/preview/ Exception Value: {'oscar@hotmail.com': (550, b'5.1.1 <oscar@hotmail.com>: Recipient address rejected: hotmail.com')}[enter image description here][1] -
changing name of a form in template tag without effecting models.py in django
hello i want to change the name in a template while rendering a form in django i'm able to change it in template only if i made change in my models.py but i want to know if is there any way where i can change the name of a particular form field without effecting my models.py i'm able to change the way form field can render only if i have changed the models.py but whenever i do so i have got an error saying no such table: login_record class Record(models.Model): choice1 = (('O Positive', 'O Positive'), ('O Negative', 'O Negative'), ('A Positive', 'A Positive'), ('A Negative', 'A Negative'), ('B Positive', 'B Positive'), ('B Negative', 'B Negative'), ('AB Negative', 'AB Negative'), ('AB Positive', 'AB Positive'), ) blood_TYPE = models.CharField(max_length=20, choices=choice1, default='O Positive') staff = models.CharField(max_length=20, default=' ') id_no = models.CharField(max_length=20, default=' ') donar_name = models.CharField(max_length=30) units = models.FloatField(default=0, validators=[MinValueValidator(0)]) date = models.DateField() class Meta: ordering = ['-date'] def __str__(self): return self.id_no here is my models.py class DonateForm(forms.ModelForm): choice1 = (('O Positive', 'O Positive'), ('O Negative', 'O Negative'), ('A Positive', 'A Positive'), ('A Negative', 'A Negative'), ('B Positive', 'B Positive'), ('B Negative', 'B Negative'), ('AB Negative','AB Negative'), ('AB Positive','AB Positive'), ) blood_group … -
How can i use the "user" table on mysql instead of the "auth_user" table which is the default from the django site?
How can i use the "user" table on mysql instead of the "auth_user" table which is the default from the django site? def login_user(request): if request.method == 'POST': form = AuthenticationForm(request=request, data=request.POST) if form.is_valid(): user_id = form.cleaned_data.get('user_id') password = form.cleaned_data.get('password') user = authenticate(user_id=user_id, password=password) if user is not None: login(request, user) messages.info(request, f"You are now logged in as {user_id}") return redirect('/') else: messages.error(request, "Invalid username or password.") else: messages.error(request, "Invalid username or password.") form = AuthenticationForm() return render(request=request, template_name="login.html", context={"form": form}) code from views.py -
How do I get the current user from the queryset filter method?
I want to show a list of store information for the current user model.py class User(AbstractUser): email = models.EmailField(max_length=100, blank=True, null=True) class Store(models.Model): u_id = models.ForeignKey(User, on_delete=models.CASCADE, null=True) store_name = models.CharField(max_length=30) business_number = models.IntegerField() serializers.py class StoreSerializer(serializers.ModelSerializer): current_user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) class Meta: model = Store fields = ('url', 'id', 'u_id', 'store_name', 'business_number', 'title', 'content', 'image', 'current_user') views.py class MyStoreDetailView(generics.ListCreateAPIView): permission_classes = [IsOwnerOrReadOnly] queryset = models.Store.objects.filter(u_id=request.uer) # how to get current user serializer_class = serializers.StoreSerializer -
Can't login with super user created account in Python 3.8
Before i go forward, I know this is a commonly asked question but I have searched the top questions related to this, and none of it seems to be helping.. Following: https://docs.djangoproject.com/en/2.2/intro/tutorial02/ What I have done: py manage.py createsuperuser Created user I have confirmed the user is a superuser with: from django.contrib.auth.models import User active_staff = User.objects.filter(is_active=True, is_staff=True) This will then list the super users Although, when I do something like: u = User(username="admin") u.is_staff >> False u.is_superuser >> False Why is this? I also then manually set to true, save(), then check, and it's now True. Try to log in, doesn't work. restart shell and check, it's back to false. I tried the accepted answer here: Can't login to django admin after creating a super user with a custom user model This: Admin page on django is broken None have helped. If there is anything i need to copy/paste from my Djnago app to help, pleaes let me know. I am new with Python and Django so I'm not exactly sure what to add to this question.