Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: checkbox values not printing to new template
I am working on a Django project that serves as a grocery store. I am trying to set it up so that when people click on checkboxes and press the confirm purchase button, then the values from the checkboxes will print to a new HTML template. The problem I am having is that when I go to the new template it doesn't print the values from the checkboxes. Views.py class PostListView(ListView): model = Post template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' def inventory(request): products = request.POST.getlist('products') for product in products: a = Post.objects.get(title=product) a.quantity = a.quantity -1 a.save() print(products) return render(request, 'blog/confirm.html') Home.html {% extends "blog/base.html" %} {% block content %} <form action="{% url 'inventory' %}" method="POST" id="menuForm"> {% for post in posts %} {% if post.quantity > 0 %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2">{{ post.category }}</a> </div> <h2><a class="article-title" >{{ post.title }}</a></h2> <p class="article-content"> Price: ${{ post.Price }}</p> <p class="article-content"> Sale: ${{ post.Sale }}</p> <input type="checkbox" id="product_{{ post.id }}" value="{{ post.title }}" form="menuForm" name="products" > Inventory count: {{ post.quantity }} </input> </div> </article> {% else %} {% endif %} {% endfor %} <button type="submit" form="menuForm">Confirm Purchase</button> </form> {% endblock content %} confirm.html {% extends … -
Post input of choicefield into django models
I am building a basic form through which data can be entered into django model database. Everything works fine except the choicefield which does not post value to the database.I want the user to select from 'Morning' and 'Evening' (default value should be blank) which can then be posted to 'time' model. Following is my models.py: date = models.DateTimeField(auto_now_add=True, null=True) time = models.CharField(max_length=200, null=True, blank=True) cow1 = models.FloatField(null=True, blank=True) cow2 = models.FloatField(null=True, blank=True) cow3 = models.FloatField(null=True, blank=True) cow4 = models.FloatField(null=True, blank=True) Views.py: def home(request): if request.method=="POST": cow1 = request.POST.get("cow1", False) cow2 = request.POST.get("cow2", False) cow3 = request.POST.get("cow3", False) cow4 = request.POST.get("cow4", False) time = request.POST.get("time", False) ins = models.cow(cow1=cow1, cow2=cow2, cow3=cow3, cow4=cow4, time=time) ins.save() return render(request, 'dataentry/home.html') And home.html: <form action = "" method = "POST"> {% csrf_token %} <label for="cow1">cow1</label> <input id="cow1" type="number" name="cow1"> <label for="cow2">cow2</label> <input id="cow2" type="number" name="cow2"> <label for="cow3">cow3</label> <input id="cow3" type="number" name="cow3"> <label for="cow4">cow4</label> <input id="cow4" type="number" name="cow4"> <label for="time">Time</label> <select form="time" name="time" id="time"> <option value="time">Morning</option> <option value="time">Evening</option> </select> <input type="submit" value="OK"> </form> Little help will be appreciated. THANKS! -
Programming the MIT Beergame in Django
I am at the moment trying to setup the MIT Beergame with a combination of Django + Channels + A-Frame for my professor. I have some experience of writing websites in Django but I've never programmed something on a comparable complexity scale as the Beergame in Django and I'm not sure how to structure everything correctly. In the game orders have to be passed from player to player in a turn-based manner with some delay and the overall costs of inventory and backorders have to be calculated every round. So I'm asking myself now: Which logic has to be in the model layer? Can I do all the calculations there? Should I rather put everything in the front-end and read it out and send it to the database with JS? How do I automatically setup a new channels instance if there are enough players in the lobby? How can I combine everything with channels to optimize usability and performance? This is how I structured the model layer so far (more a less a draft): import json import random import string from collections import defaultdict from django.core.serializers.json import DjangoJSONEncoder from django.db import models from tum_vr.users.models import User # TODO: Decide where … -
How to pause and continue a function in python
I am very new to python, i have a function where am uploading a csv file and saving it in my db, it's working, but what i want to do now is that suppose the csv file am uploading has 500 rows, so when i upload it instead of saving the file with 500 rows it should take 100 rows from that file save it and then move to another 100 save it as another file and so on till the whole file is completed. Here is my code: def bulk_uploads_trial_users_upload(request): if is_super_admin_authonticated(request) : try: data = json.loads(request.body) super_admin = int(request.session.get('super_admin_id')) file_name = (BulkUpload.objects.all().count()) + 1 file_ext = data.get('Name').split('.')[-1] current_timestamp = int(datetime.datetime.now().timestamp()) print(data.get('File', None)) Info = BulkUpload.objects.create( upload_type = 1, file_path = save_document(data.get('File', None), 'csv_upload', file_name, file_ext), upload_timestamp = current_timestamp, process_status = 1, created_by = super_admin ) Info.file_name = str(file_name) + '.' + file_ext Info.save() return HttpResponse(json.dumps({"status": 1}), content_type='application/json') except Exception as e: print(e) return HttpResponse(json.dumps({"status": 0}), content_type='application/json', status=401) else: return HttpResponse(json.dumps({"status": 0}), content_type='application/json', status=403) -
Error in Dockerizing Django with Postgres and Pgadmin
docker- compose.yml version: "3.3" services: db: image: postgres environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres # - POSTGRES_HOST_AUTH_METHOD="trust" - POSTGRES_PORT=5432 ports: - "5432:5432" pgadmin: image: dpage/pgadmin4 depends_on: - db ports: - "5051:80" environment: PGADMIN_DEFAULT_EMAIL: pgadmin4@pgadmin4.com PGADMIN_DEFAULT_PASSWORD: pgadmin4 restart: always web: build: . command: python manage.py runserver 0.0.0.0:8000 ports: - "8000:8000" links: - db:db depends_on: - db settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': 5432, } } Error while executing python3 manage.py makemigrations: django.db.utils.OperationalError: could not translate host name "db" to address: Temporary failure in name resolution I tried adding - POSTGRES_HOST_AUTH_METHOD="trust" however the error remained. I also tried changing 'HOST': 'db' to 'HOST': 'localhost' and then I can run the make migrations but I get this error: Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? I saw many similar questions but none of the answers seems to fix the problem. Any suggestions according to my docker-compose and setting? -
Django StatReloader is not watching files in app
I have two apps in my project, products app and users app that I created with command python manage.py createapp and I added the two apps to the INSTALLED_APPS in settings.py every model in both apps is registered in admin.py and tested in the shell and the admin page. My problem is that everything except the models.py file in the products app is not "being watched" or something like that, I tried to use signals.py in the products app but didn't work, I used the same code in the users app and it worked (I edited the import lines). Also when I tried to make a class-based view in the users app extend a fictional class running python manage.py runserver gives an error but doing the same thing in the products app will run the program successfully. Does anyone know how can I solve this? INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users.apps.UsersConfig', 'products', 'crispy_forms', ] -
How to add data from one model to other django?
I am using generics to represent views class PersonRetrieveView(generics.ListAPIView): queryset = Person.objects.all() serializer_class = PersonSerializer and class CommentRetrieveView(generics.RetrieveAPIView): queryset = Comment.objects.all() serializer_class = CommentSerializer Person data looks like { "id": 2, "user": { "first_name": "Testuser", "last_name": "TestUser1", "id": 2 }, "name": "Test 2", "city": "California", "status": "NotActive", "phone_number": "9876543222", "age": 22, "height": 180 } and Comment { "id": 1, "comment": "test", "person": 2 } Comment linked to Person by id. How can i add data from comment to PersonRetrieveView ? Serializers looks like this class PersonSerializer(serializers.ModelSerializer): user = UserSerializer() # comment = CommentSerializer() class Meta: model = Person fields = '__all__' class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = '__all__' -
how to pin ssl certificate in andoid and django?
my team and me developing an android app with kotlin, Django, and Django rest framework.. they asking we need SSL pinning to the app side. any changes required in the Django REST API endpoints!. we already using HTTPS on the server-side with let's encrypt.. any additional changes required in server-side API endpoints!. -
botocore.exceptions.ClientError (InvalidAccessKeyId)
I am new to docker and in our dev env, we have S3 access key id and AWS secret access key. We are using the digital ocean spaces to offload our dev env static files. We need to run the collect static command manually to update the media and static files. The whole process was working fine for the last couple of months but I am recently facing this error. After some research, I updated the Acess key id and AWS secret access key but this error remains the same. Can anyone please help me with this issue? enter image description here -
problem when restoring postgresql database for a django application
I am trying to transfer my testing server's database to my working PC. So I do this: (Postgres 12.5) pg_dump -U nutrition -d mednutrition_db --clean -f mednut_bak.sql and then I try to restore it like this on my Postgres 9.5 psql -U chris mednutrition_db < mednut_bak.sql This simple method was working fine for me. But now it seems there is a problem which I cannot solve. I noticed that django creates ID fields using this default value (for example): nextval('django_migrations_id_seq'::regclass) However, when I restore the database, the default value for the ID fields remains empty, and of course I cannot insert any new data to the restored database. How can I resolve this? -
how can i use the numpy in django?
I'm trying to do a process numpy,matplotlib, scipy. but it raise an error that i dont know what is it. my code is: def add_user_order(request): new_order_form = sp_UserNewOrderForm(request.POST or None) if request.method == 'POST': upload_file = request.FILES['document'] if not upload_file.name.endswith('.xlsx'): return redirect('/error1') read = pd.read_excel( upload_file) if new_order_form.is_valid(): order = sp_Order.objects.filter(owner_id=request.user.id).first() if order is None: order = sp_Order.objects.create(owner_id=request.user.id) fs = FileSystemStorage() fs.delete(upload_file.name) name = new_order_form.cleaned_data.get('name') x = read['x'].tolist() y = read['y'].tolist() poly = np.polyfit(x, y, 10) poly_y = np.poly1d(poly)(x) smooth = [round(i, 3) for i in poly_y] poly = np.polyfit(x, y, 10) poly_y = np.poly1d(poly)(x) hull = [round(i, 3) for i in poly_y] for filename in os.listdir('spectrum_order/zip_file'): if filename.endswith(".xlsx") or filename.endswith(".xls"): read = pd.read_excel('spectrum_order/zip_file/' + filename) labels = read['x'].tolist() b = [float(n) for s in labels for n in s.strip().split(' ')] x1 = b[::2] y1 = b[1::2] correlation, p_value = stats.pearsonr(y, y1) if correlation >= 0: plt.plot(x, y) plt.plot(x1, y1) plt.savefig(f'./spectrum_order/image/{filename}.png', dpi=300) return correlation return redirect('/open_sp_order') error is: 'numpy.float64' object has no attribute 'get' when I delete line 29 to 41(for filename...) this code work. please help. -
Which authentication Mechanism to choose to develop web app using Angular + Django rest framework
Can we use the Token/JWT authentication mechanisms to integrate the Django rest framework application with the Angular frontend? Or we need to use session authentication to develop a web app? -
TypeError: ModelBase object got multiple values for keyword argument Django
Got an error - Exception Value: ModelBase object got multiple values for keyword argument voucher. Trying to insert two rows with these two dictionaries. if form.is_valid(): debit_tr ={ 'voucher': newvoucher, 'descirption': 'Purchase Order: '+ self.request.POST.get('purchase_id'), 'debit':self.request.POST.get('total_amount'), 'account':self.request.POST.get('debit_account') } credit_tr ={ 'voucher': newvoucher, 'descirption': 'Purchase Order: '+ self.request.POST.get('purchase_id'), 'credit':self.request.POST.get('paid_amount'), 'account':self.request.POST.get('credit_account') } j = Journal(**debit_tr, **credit_tr) j.save() -
How to change the tz in records stored by the usage of django-auditlog in django admin panel
I am using the django-auditlog library to store audit logs concerning some of my models. I noticed that despite the fact that I have defined the time zone in settings.py all the models containing fields of type DateTimeField are stored in UTC time in my admin panel in Log entries section. Here is my settings.py part concerning time and time zone configurations : USE_L10N = True TIME_ZONE = 'Europe/Athens' USE_TZ = True What to do in order the log audit records to be in timezone defined by me and not in UTC? -
compare html input dates in python
I have two Html date inputs and I want to compare them in my Django views this is my views.py start = request.POST.get('start_date') end = request.POST.get('end_date') d1 = time.strptime(start, "%Y-%m-%d") d2 = time.strptime(end, "%Y-%m-%d") if d1 > d2: return False I have entered 05-05-2020 in start_date and 06-05-2020 in the end_date my javascript function is comparing dates correctly but the python function is returning False in these values I have also tried d1 = datetime.datetime.strptime(start, "%Y-%m-%d") d2 = datetime.datetime.strptime(end, "%Y-%m-%d") but the same issue what am I doing wrong? -
Djongo + Django + MongoDB Atlas DatabaseError when trying to reset password
So I'm trying to create a password reset link for a website that is running on Django and uses Djongo. Whenever I enter a password and click on the reset password button, this error occurs: Environment: Request Method: POST Request URL: http://localhost:8000/password-reset/ Django Version: 3.1.4 Python Version: 3.8.3 Installed Applications: ['blog.apps.BlogConfig', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_cleanup'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\Harry\anaconda3\envs\agrifarm\lib\site-packages\djongo\cursor.py", line 51, in execute self.result = Query( File "C:\Users\Harry\anaconda3\envs\agrifarm\lib\site-packages\djongo\sql2mongo\query.py", line 783, in __init__ self._query = self.parse() File "C:\Users\Harry\anaconda3\envs\agrifarm\lib\site-packages\djongo\sql2mongo\query.py", line 875, in parse raise e File "C:\Users\Harry\anaconda3\envs\agrifarm\lib\site-packages\djongo\sql2mongo\query.py", line 856, in parse return handler(self, statement) File "C:\Users\Harry\anaconda3\envs\agrifarm\lib\site-packages\djongo\sql2mongo\query.py", line 932, in _select return SelectQuery(self.db, self.connection_properties, sm, self._params) File "C:\Users\Harry\anaconda3\envs\agrifarm\lib\site-packages\djongo\sql2mongo\query.py", line 116, in __init__ super().__init__(*args) File "C:\Users\Harry\anaconda3\envs\agrifarm\lib\site-packages\djongo\sql2mongo\query.py", line 62, in __init__ self.parse() File "C:\Users\Harry\anaconda3\envs\agrifarm\lib\site-packages\djongo\sql2mongo\query.py", line 152, in parse self.where = WhereConverter(self, statement) File "C:\Users\Harry\anaconda3\envs\agrifarm\lib\site-packages\djongo\sql2mongo\converters.py", line 27, in __init__ self.parse() File "C:\Users\Harry\anaconda3\envs\agrifarm\lib\site-packages\djongo\sql2mongo\converters.py", line 119, in parse self.op = WhereOp( File "C:\Users\Harry\anaconda3\envs\agrifarm\lib\site-packages\djongo\sql2mongo\operators.py", line 476, in __init__ self.evaluate() File "C:\Users\Harry\anaconda3\envs\agrifarm\lib\site-packages\djongo\sql2mongo\operators.py", line 465, in evaluate op.evaluate() File "C:\Users\Harry\anaconda3\envs\agrifarm\lib\site-packages\djongo\sql2mongo\operators.py", line 465, in evaluate op.evaluate() File "C:\Users\Harry\anaconda3\envs\agrifarm\lib\site-packages\djongo\sql2mongo\operators.py", line 279, in evaluate raise SQLDecodeError The above exception ( Keyword: None Sub SQL: None FAILED SQL: … -
Why is Heroku giving me an H10 error when I deploy Django app
Hi all first time deploying an app and working with django. it keeps giving me the error code H10. I'm not sure what i'm doing wrong here are my files. I'm not sure what to do i've tried so many guides and tutorials and followed the documentation. If anyone could give me some guidance and let me know if they see anything obvious that wrong it would be greatly appreciated! Procfile web: python manage.py runserver 0.0.0.0:$PORT --noreload Requirements.txt asgiref==3.3.1 astroid==2.4.2 colorama==0.4.4 Django==3.1.3 django-crispy-forms==1.10.0 django-mysql==3.9.0 djangorestframework==3.12.2 gunicorn==20.0.4 isort==5.6.4 lazy-object-proxy==1.4.3 mccabe==0.6.1 mysql-connector-python==8.0.21 mysqlclient==2.0.1 pylint==2.6.0 pytz==2020.4 six==1.15.0 sqlparse==0.4.1 toml==0.10.2 whitenoise==5.2.0 wrapt==1.12.1 settings.py from pathlib import Path import datetime import os import django_heroku import dj_database_url # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '-%f#+^u0#uxq0qm!$o-zvmo)&tof(t#g$n#q01v2&%&$$1o9gc' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = false ALLOWED_HOSTS = ['myrecipebook1.herokuapp.com','127.0.0.1'] AUTH_USER_MODEL = 'users.Custom_User' # Application definition INSTALLED_APPS = [ 'rest_framework', 'users', 'recipe', 'django_mysql', 'drf_yasg', 'rest_framework_simplejwt.token_blacklist', #S'pillow', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] SWAGGER_SETTINGS={ 'SECURITY_DEFINITIONS' : { 'Bearer': { 'type' : 'apiKey', 'name' … -
Using a model.field to filter many-to-many checkbox in django
i am trying to make a job allocation app in django admin. I have a Create Job page, where you can filter Employees based on availability and skill level(1-4) (e.g: ib_unstuffing = 1). I want to be able to do it on the same form where a user inputs a number on ib_unstuffing, and the many-to-many Field displays all Employees with ib_unstuffing = 1, but i am currently getting the error: TypeError: Field 'ib_unstuffing' expected a number but got <django.db.models.fields.IntegerField: ib_unstuffing>. Any help would be greatly appreciated thank you! this is my Models.py: class Job(models.Model): emp_no = models.ForeignKey(Employee, db_column='emp_no', related_name = 'employeeSalaries', on_delete=models.CASCADE) title = models.CharField(max_length=50) qty = models.IntegerField() ib_admin = models.IntegerField() ib_unstuffing = models.IntegerField() ib_putaway = models.IntegerField() salary_amount = models.IntegerField() emp_assigned = models.ManyToManyField(Employee, limit_choices_to = {'available': 1, 'ib_unstuffing': ib_unstuffing}) from_date = models.DateField() to_date = models.DateField() admin.py class JobAdmin(admin.ModelAdmin): formfield_overrides = { models.ManyToManyField: {'widget': CheckboxSelectMultiple}, } -
Using Django Admin FilteredSelectMultiple form widget with the Add button
I'm trying to use the Django admin FilteredSelectMultiple within a user form, but I also want to include the add button and cannot work out how. This is my form field definition search_areas = forms.ModelMultipleChoiceField( queryset = SearchArea.objects.all(), widget= FilteredSelectMultiple("Postcodes", is_stacked=False), required=True ) And the model: class SearchArea (models.Model): """ This is a Search Area """ post_code = models.CharField( max_length=51, unique=True, ) lat = models.DecimalField( max_digits=9, decimal_places=6, blank=True, null=True, help_text='This will be populated using the postcode entered on save' ) lng = models.DecimalField( max_digits=9, decimal_places=6, blank=True, null=True, help_text='This will be populated using the postcode entered on save' ) This provides me with the horizontal filter/select widget, but not the add button. How can I include that? -
Генератор тем на Django [closed]
коллеги! есть задача - написать генератор тем в админке django, то есть - заходим в админку, выбираем (условно) красный цвет, сохраняем и после этого ui сайта меняется на красный. причем не только цвет, а шрифты и т.д. существуют ли какие-нибудь готовые решения для данной задачи? спасибо! -
Problem querying a specific django object correctly
In my (basic) fantasy football app I'm building, I have each player/position represented by an individual model object. Like so. Here's one such model/position. class Quarterback(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=20, blank=True) I also have a "Team" model which has information on team name, user, and players in the team. The main purpose of this object is because I want to display a list of all users and their teams and their team's total score so that each user can see how everyone else is scoring. class Team(models.Model): team_name = models.CharField(max_length=255, blank=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) quarter_back = models.ForeignKey(Quarterback, on_delete=models.CASCADE, null=True) running_back = models.ForeignKey(Runningback, on_delete=models.CASCADE, null=True) wide_receiver = models.ForeignKey(Widereceiver, on_delete=models.CASCADE, null=True) tight_end = models.ForeignKey(Tightend, on_delete=models.CASCADE, null=True) kicker = models.ForeignKey(Kicker, on_delete=models.CASCADE, null=True) The problem I'm having though is assigning a total score. What I'm trying to do is compare the players'names in Team to a list of players and scores that I've pulled from an api. Let's call it "player_data." If the player in the Team object is in the player_data object, I can then assign the player's score to a variable called "totalscore", tally it, render it to my template, etc. But, I'm having trouble with … -
Django REST AttributeError 'dict' object has no attribute 'pk'
Im trying to do django rest api with Django Rest Framework. The issue Im experiencing is 'dict' object has no attribute 'pk' when I try to display agregated data. I can see in the trace serializer.data displayed as it should be, the format is as follows: [{'maint_window':'W1-12:00-CET', 'total':'10'}, {'maint_window':'W2-12:00-CET', 'total':'5',} {'maint_window':'W3-12:00-CET', 'total':'22'}] But it seems that I`m not returning the correct format in the view, or in the serializer. models.py: from django.db import models class Server(models.Model): name = models.CharField(max_length=60) fqdn = models.CharField(max_length=60) maint_window = models.CharField(max_length=60) def __str__(self): return self.name serializer.py: class ServerSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Server fielsds='__all__' views.py: class OpsCalendarViewSet(viewsets.ModelViewSet): """ API endpoint that shows ops calendar """ queryset = Server.objects \ .filter(~Q(maint_window__contains='MW') & \ ~Q(maint_window__contains='Change') & \ ~Q(maint_window__contains='Individual')) \ .values('maint_window') \ .annotate(total=Count('name'))\ .order_by('maint_window') serializer_class = ServerSerializer permission_classes = [permissions.AllowAny] And the error itself: lookup_value = getattr(obj, self.lookup_field) AttributeError: 'dict' object has no attribute 'pk' -
Company internal User creation in django without a signup url
I am trying to create an authentication system for a Company and the Company would want to have its admin create users from his endpoint and then the users can receive an email, where they can click a link, a link shall just have a password one field and password two field and the moment they click the save button they would be able to avtivate their account and be redirected to the dashboard based on the category they belong to. Below is my code. class UserManager(BaseUserManager): USER_TYPE_CHOICES = [ ('supervisor', 'SUPERVISOR'), ('operator', 'OPERATOR'), ('hofosm', 'HEAD OFFICE ORDINARY STAFF MEMBER'), ('hofom', 'HEAD OFFICE MANAGEMENT'), ('hofis', 'HEAD OFFICE IT STAFF'), ] def create_user( self, email, is_superuser=False, password=None, is_active=True, is_staff=False, is_admin=False): if not email: raise ValueError("Enter Valid Email") user_obj = self.model( email=self.normalize_email(email) ) user_obj.set_password(password) user_obj.staff = is_staff user_obj.admin = is_admin user_obj.active = is_active user_obj.save(using=self._db) return user_obj def create_superuser(self, email, password=None, **extra_fields): user=self.create_user( email, password = password, is_staff = True, is_admin =True, is_superuser=True, **extra_fields ) return user class User(AbstractBaseUser, PermissionsMixin): title = models.CharField(max_length=341, choices = USER_TITLE_CHOICES) category = models.CharField(max_length=341, choices = USER_TYPE_CHOICES, default='operator') first_name = models.CharField(max_length =32, blank=True, null=True) middle_name = models.CharField(max_length =32, blank=True, null=True) company_branch= models.ForeignKey( 'company_setup.CompanyBranch', related_name='employees', on_delete=models.SET_NULL, null=True, blank=True ) … -
Django templates - how to strictly check for equality of a string
I struggling to solve the following: I am customizing django tabular inline template which contains several fields. I have a condition {% if field.field.name == 'productid' %} ... {% endif %} However there are two fields that have the ... condition applied which is "productid" and "distributionid price productid" - both contain the productid word. However, I want only the former to have it. How can I make this condition more strict? Any help will be much appreciated. -
How to make Django send request itself
I need to make GET request, that executes himself once per 3 day, I found things about celery and Redis, but I don't understand how to send request. I mean, if I use celery, I need to wrap function with @app.task, so it can't be method GET of a class, right? And so I can't use method of a class outside of class, cause I don't have self (instance of a class). So how do I make Django send request to itself?