Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
use record from same model as foreignkey in django
my model is as follows : class Profile(model.Models): name = models.CharField(max_length = 20) full_name = models.CharField(max_length = 20) husband_spouse = models.ForeignKey(Profile, on_delete=models.CASCADE) on doing python manage.py makemigrations I get the following error : NameError: name 'Profile' is not defined Question : How should I use another record of the same model as a foreignkey in my current model TIA -
AttributeError: 'list' object has no attribute 'order_by'
I was trying to combine two queryset objects by itertools chain python predefine function and filter this with order_by. but i'm getting an AttributeError: 'list' object has no attribute 'order_by'. If anybody could figure out where i'm doing thing wrong then would be much appreciated. thank you so much in advance. views.py : try: qs = Conversation.objects.filter( Q(chat__from_user=user) & Q(chat__to_user=to_user)) qs_2 = Conversation.objects.filter( Q(chat__from_user=to_user) & Q(chat__to_user=user)) except: raise ValidationError({"message":"bad request"}) all_qs = list(chain(qs, qs_2)).order_by('-created_on') -
Django Redirecting to a created view (pk)
I am trying to redirect to a created post after filling up the form. I tried following Django redirect to created post after form but I encountered this error TypeError at /inquiry/ inquiry() missing 1 required positional argument: 'pk' def inquiry(request,pk): form = RescueeForm() if request.method == 'POST': form = RescueeForm(request.POST) if form.is_valid(): form.save() return redirect ('rescuee' form.pk) context = { 'form' : form } return render(request, "inquiry_page.html", context) urls.py urlpatterns = [ path('', views.index, name='index'), path('inquiry/', views.inquiry, name='inquiry'), path('rescuee/<int:pk>', views.rescueeview, name='rescuee'), ] -
Django filtering in bootstrap
I try to filter username from my all users in django and I need to have some forms in bootstrap. What I did is: <div class="form-group col-4 text-left"> <label for="exampleFormControlInput1">User Name</label> <input type="text" class="form-control" id="exampleFormControlInput1" placeholder="username" {{customer_filter.form.username}}> </div> It is working but in my page I have extra > printed on my page. I don't know how to use {{customer_filter.form.username}} in bootstrap in label tag. -
ValueError('Related model %r cannot be resolved' % self.remote_field.model)
while using AUTH_USER_MODEL django throwing error. while adding my own custom model to authenticate login.when i run command python manage.py migrate it give me an error, i actually want to create a custom user model to authenticate login to my own custom admin login my settings.py import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'g4!we933keyd4p*2z*1rz)=zl%s9qi#21^to$@*79e6rz8bj1e' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'farmingwave',] 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', ] STATIC_URL = '/static/' STATICFILES_DIRS =[ os.path.join(BASE_DIR,'static') ] EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'seo.guru.tech00@gmail.com' EMAIL_HOST_PASSWORD = 'working12090' AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.ModelBackend',] AUTH_USER_MODEL = 'farmingwave.CustomUser' my models.py from django.db import models from django.forms import ModelForm from django.core.validators import RegexValidator from django.contrib.auth.models import AbstractUser, BaseUserManager from django.conf import settings class CustomUser(AbstractUser): Username = models.CharField(max_length=255, unique=True,default='root') password = models.CharField(max_length=50,) my admin.py from django.contrib import admin from .models import contactForm from .models import writerForm from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from .forms import LoginForm from .models import CustomUser class CustomUserAdmin(admin.ModelAdmin): form = LoginForm model = CustomUser admin.site.register(CustomUser,CustomUserAdmin ) class Meta: db_table = 'user_auth' class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) -
How can i override the save() method in admin page
it maybe look like a simple question, but i been struggling for weeks now, i want to override the save method in admin page, for a model name Transaction that i created, i want to pre save each transaction by groups.. lets say for example i have created 2 groups (Test1, Test2) and i assigned users to each group, and a user from group Test1 made a transaction and saved it. i want all users from Test1 group to see the transaction and modify it, but not Test2 groups members. I override save method and queryset method, but yet it still not working. any ideas ? here is my code class TransactionAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): obj.user = request.user.groups print(obj.user) super().save_model(request, obj, form, change) def get_queryset(self, request): qs = super().get_queryset(request) if request.user.is_superuser: return qs return qs.filter(group__in=request.user.groups.all()) -
Adding "group" field in Django User Admin
I am trying to add a "group" field to show group permissions on the user panel in Django 3.1.2. I tried combining this and this, but always end up in either end up with The model User is already registered with 'auth.UserAdmin' or The model User is not registered (when trying to unregister first): from django.contrib import admin from django.contrib.auth.models import User # fails in "model User not registered" admin.site.unregister(User) #fails in already registered with auth.UserAdmin @admin.register(User) class UserAdmin(admin.ModelAdmin): def group(self, user): return ' '.join([g.name for g in user.groups.all()]) list_display = ['username', 'email', 'first_name', 'last_name', 'is_active', group] list_filter = ['groups', 'is_staff', 'is_superuser', 'is_active'] How would I correctly register my custom UserAdmin? -
Django adding data into model from nested json returning TypeError: 'NoneType' object is not subscriptable
I am using a third-party API to get data and add it into my database via objects.update_or_create() method. This data has many records and some of the fields in the response only exists for certain records. Below the a snippet of the JSON that is returned from the API. However this data is only present for some of the records in the JSON response. When I try to add this data into my model, I am getting the following error: 'f_name': i.get('card_faces')[0].get('name'), TypeError: 'NoneType' object is not subscriptable I am trying to have it so that if the card_faces field exists, True is added to the card_face column in the database, and then the card_faces name to the database. If card_faces doesn't exist, then False is added to the card_face column in the database, and subsequent fields are null. JSON: { "data": [ "name": "Emeria's Call // Emeria, Shattered Skyclave", "card_faces": [ { "object": "card_face", "name": "Emeria's Call" }, { "object": "card_face", "name": "Emeria, Shattered Skyclave" } ], ] } views.py: for i in card_data: Card.objects.update_or_create( id=i.get('id'), defaults={ 'name': i.get('name'), 'card_faces': i.get('card_faces'), 'f_name': i.get('card_faces')[0].get('name'), 'b_name': i.get('card_faces')[1].get('name'), } ) -
How to give the json data in post api request in django rest framework
I am new to the Django rest framework, please guide me where I made a mistake, I want to make the API that takes two arguments cat name (which is char field) cat fields (which is JSON field) I want to put dynamic JSON fields, like it upon the client that they will add the 4 fields data with key pairs in JSON or any number of fields, I hope so you all guys would understand my query Please help me, it will really appreciate Here is my Views.py @api_view(['POST']) @parser_classes([JSONParser]) def add_cateogry_with_fields(request, format=None): if request.method == "POST": insert_Serializers = AddCategoryWithFieldsSerializer(data=request.data) if insert_Serializers.is_valid(): insert_Serializers.save() return Response(insert_Serializers.data, status=status.HTTP_201_CREATED) else: return Response(insert_Serializers.data, status=status.HTTP_400_BAD_REQUEST) and here is the serializer class serializer.py class AddCategoryWithFieldsSerializer(ModelSerializer): category_name = serializers.CharField(max_length=34) category_fields = serializers.JSONField() class Meta: model = CategoryModel fields = ('category_name', 'category_fields') the Model.py class is class CategoryModel(models.Model): category_id = models.AutoField(primary_key=True) category_name = models.CharField(max_length=255) category_fields = models.JSONField() parent_category = models.ForeignKey('self', on_delete=models.CASCADE, null=True) class Meta: db_table = 'category' enter image description here -
Pass id user to view function
I try pass id by template to view but I have MultiValueDictKeyError at /accounts/profile/1 <a class="nav-link" href="{% url 'accounts:profile' request.user.id %}">{{request.user}}</a> path('accounts/profile/<int:id>', views.profile, name="profile"), def profile(request, id): user = User.objects.get(id=int(request.POST[id])) return user -
Need 2 values to unpack in for loop; got 4
I'm new to Django, and trying to pass api results (dictionaries within a list) to a template using context. I have tried doing this {% if apiList != "Error..." %} {% for i in apiList %} {% for key, value in i %} {{ key }} {{ value }}<br> {% endfor %} {% endfor %} {% endif %} but I get the error Need 2 values to unpack in for loop; got 4. When I do the same code but take out the value, so it just searches for the keys, it works fine and prints out all the keys on a new line. I've also tried the following code: {% for key, value in apiList.items %} {{ key }} : {{ value }} {% endfor %} but this does not seem to work either, it does not give an error, but nothing shows on the screen. Any idea how to solve this problem? Here is my code in the views.py try: apiList = json.loads(api_request.content) except Exception as e: apiList = "Error..." return render(request, 'financials.html', {'apiList': apiList}) else: return render(request, 'financials.html', {}) Thanks! -
Django log to file by date
I am trying to create log files for Django application by using logging.handlers.TimedRotatingFileHandler class. but i am getting error. In setting.py i am adding this LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'formatters': { 'verbose': { 'format': '%(levelname)s|%(asctime)s|%(module)s|%(process)d|%(thread)d|%(message)s', 'datefmt' : "%d/%b/%Y %H:%M:%S" }, }, 'handlers': { 'default': { 'level': 'INFO', 'class': 'logging.handlers.TimedRotatingFileHandler', 'filename': os.path.join(path, 'django.log'), 'formatter': 'verbose', 'when': 'midnight', 'interval': 1, 'backupCount': 365, }, }, 'loggers': { 'django': { 'handlers': ['default'], 'level': 'DEBUG', 'propagate': True, }, }, } but I am getting following errors --- Logging error --- Traceback (most recent call last): File "/opt/rh/rh-python36/root/usr/lib64/python3.6/logging/handlers.py", line 72, in emit self.doRollover() File "/opt/rh/rh-python36/root/usr/lib64/python3.6/logging/handlers.py", line 397, in doRollover if self.backupCount > 0: TypeError: '>' not supported between instances of 'str' and 'int' Call stack: File "/home/mohsin/demo/bin/gunicorn", line 8, in sys.exit(run()) File "/home/mohsin/demo/lib64/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 58, in run WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run() File "/home/mohsin/demo/lib64/python3.6/site-packages/gunicorn/app/base.py", line 228, in run super().run() -
i have proplem with pip resolver 2020
i am trying puplish my django project on Cpanel i had used pip install django==2.1 --use-feature=2020-resolver for install all my package but i got following error this error han't appear on my PC Applying authtoken.0001_initial... OK Applying authtoken.0002_auto_20160226_1747...Traceback (most recent call last): File "/home/aeraeg/virtualenv/python/3.7/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.errors.SyntaxError: syntax error at or near "WITH ORDINALITY" LINE 6: FROM unnest(c.conkey) WITH ORDINALITY co... ^ ....... line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/home/aeraeg/virtualenv/python/3.7/lib/python3.7/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File "/home/aeraeg/virtualenv/python/3.7/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/home/aeraeg/virtualenv/python/3.7/lib/python3.7/site-packages/django/db/utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/home/aeraeg/virtualenv/python/3.7/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: syntax error at or near "WITH ORDINALITY" LINE 6: FROM unnest(c.conkey) WITH ORDINALITY co... ^ -
Failed to load module script: The server responded with a non-JavaScript MIME type of "text/plain". Strict MIME type checking is enforced for module
I followed the this video while installing the django debug toolbar as well as the docs. However, I just cannot get it to work. The mime type error keeps popping up in the console tab of the dev tools. settings.py from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'this is secret' DEBUG = True if DEBUG: import mimetypes mimetypes.add_type("application/javascript", ".js", True) INTERNAL_IPS = [ '127.0.0.1', ] ALLOWED_HOSTS = [ 'localhost', '127.0.0.1', ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', ] MIDDLEWARE = [ 'debug_toolbar.middleware.DebugToolbarMiddleware', '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', ] ROOT_URLCONF = 'demo.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'demo.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_in_env')] VENV_PATH = os.path.dirname(BASE_DIR) STATIC_ROOT = os.path.join(VENV_PATH, 'static_root') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(VENV_PATH, 'mdeia') # … -
Understanding Model Permissions in Django 3.1
I have some troubles understanding how Django 3.1 checks permissions, especially how model permissions versus default permissions are handled. I have the following model: from django.db import models class MyModel(models.Model): class Meta: permissions = [("finalize", "Can finalize"),] is_final = models.BooleanField(default = False) which defines a new finalize permission for this model. With the model along we have a model admin: from django.contrib import admin from django.contrib.auth import get_permission_codename from .models import * class MyModelAdmin(admin.ModelAdmin): actions = ['set_final', 'remove_final'] def set_final(self, request, queryset): queryset.update(is_final=True) set_final.allowed_permissions = ('finalize',) def remove_final(self, request, queryset): queryset.update(is_final=False) remove_final.allowed_permissions = ('finalize',) # Permissions def has_change_permission(self, request, obj = None): if obj and obj.is_final: return False codename = get_permission_codename('change', self.opts) print("has_perm(change) : %s.%s : %s" % (self.opts.app_label, 'change', request.user.has_perm('%s.%s' % (self.opts.app_label, 'change')))) print("has_perm(codename): %s.%s : %s" % (self.opts.app_label, codename, request.user.has_perm('%s.%s' % (self.opts.app_label, codename)))) return request.user.has_perm('%s.%s' % (self.opts.app_label, codename)) def has_finalize_permission(self, request, obj = None): codename = get_permission_codename('finalize', self.opts) print("has_perm(finalize): %s.%s : %s" % (self.opts.app_label, 'finalize', request.user.has_perm('%s.%s' % (self.opts.app_label, 'finalize')))) print("has_perm(codename): %s.%s : %s" % (self.opts.app_label, codename, request.user.has_perm('%s.%s' % (self.opts.app_label, codename)))) return request.user.has_perm('%s.%s' % (self.opts.app_label, 'finalize')) admin.site.register(MyModel, MyModelAdmin) which defines two actions: setting and removing the is_final flag from objects. Along with it, the has_change_permission is redefined because the … -
Django Choices Object Not passing id to URL
I'm using a model with a choices field that is being displayed by a form. I want to create a delete function in my views.py but can't get it to work. I suspect it's because my model object is not passing an id, or my url just isn't picking the object's id for whatever reason. Here's my model. class Player(models.Model): PLAYER_ROLE_CHOICES = ( (1, 'Quarterback'), (2, 'Runningback'), (4, 'Widereceiver'), (5, 'Tightend'), (6, 'Kicker'), ) role = models.PositiveSmallIntegerField(choices=PLAYER_ROLE_CHOICES) Here's the delete function I'm trying to make in views.py def delete_player(request, id): player = Player.objects.get(id=id) player.delete() return redirect('show') and my url path('delete_player/<int:id>', views.delete_player, name="delete_player") I know that I obviously need an id to be passed to both the url and delete function in views.py, but I don't know how to get the id from my model. I'd appreciate any help/another set of eyes on the problem. Thanks in advance. -
I want to show a specific customers balance in a panel
I want to show a specific customers balance in a panel for that I want to fetch the specific customers balance and want to show it in a page or somewhere else.Like this example: user 1 has 100$ and user 2 has 200$ so when user 1 will login the page will show 100$ and when user 2 login he will be shown 200$.But I am confused here to complete this task.How can I do this ? I have a coin var which is working as a balance. Here is my Model for Customer : class Customer(models.Model): phone_number = models.CharField(max_length=100, default=1) email = models.EmailField( default=1) password = models.CharField(max_length=100) coin = models.FloatField(null=True, blank=True) def __str__(self): return self.phone_number def register(self): self.save() def get_customer(phone_number): try: return Customer.objects.get(phone_number=phone_number) except: return False -
Django-import-export export also related field of a model
In my project i have a model like this: models.py class e_cart(models.Model): e_uid = models.ForeignKey(User, on_delete=models.CASCADE, ) e_prodid = models.ForeignKey(p_prodotti, on_delete=models.CASCADE, verbose_name="Product") e_qta = models.IntegerField(default=0, verbose_name="Quantita") e_datain = models.DateTimeField(auto_now=True, verbose_name="Insert Data") .... I use django-import-export for export my data in admin panel and in admin.py i do: from import_export.admin import ImportExportModelAdmin class OrderAdmin(ImportExportModelAdmin): search_fields = ('onum',) list_display = ('onum', 'date', 'paid', 'onotes', 'totord', 'obank') ordering = ('-date', 'onum') Now for example the e_uid field is exported as just an id (1,2 ecc) bu i would export the select_related() filds for example e_uid.firstname, e_uid.lastname ecc How can i modify my code for export also related field of my model? so many thanks in advance -
Django-React Axios request breaks token
Everytime I do an axios request in the ComponentDidMount() for example: axiosInstance.get('/user/profile', { headers:{ "Authorization": "JWT " + localstorage.getItem('access_token') } }).then(res => { return res; }).catch(err => { console.log(err) }) OR THIS axiosInstance.get('/user/profile').then(res => { axiosInstance.defaults.headers["Authorization"] = "JWT " + localstorage.getItem('access_token'); return res; }).catch(err => { console.log(err) }) I am running a Django-React project with postgresql as my DB. I followed the guide by Toruitas on Hackernoon on how to use simple-JWT to issue my access_token and refresh_token. Everytime the axios request runs, my refresh_token becomes undefined and It just renders my whole other requests useless as my refresh_token is missing My axiosAPI - axiosInstance : import axios from "axios" import jwt from "jwt-decode" import history from "./utilities/history" const baseURL = 'http://127.0.0.1:8000/api/' const axiosInstance = axios.create({ baseURL: baseURL, timeout: '5000', headers: { 'Authorization': localStorage.getItem('access_token') ? "JWT " + localStorage.getItem('access_token') : null, 'Content-Type': "application/json", 'accept': "application/json" } }); axiosInstance.interceptors.response.use( response => response, error => { const originalRequest = error.config; // if (error.response.status === 401 && originalRequest.url === baseURL +'token/refresh/') { // history.push('/login') // return Promise.reject(error); // } if (error.response.data.code === "token_not_valid" && error.response.status === 401 && error.response.statusText === "Unauthorized") { const refreshToken = localStorage.getItem('refresh_token'); if (refreshToken) { // const tokenParts = … -
Deploying Serverless Django with Zappa through Terraform
I want to deploy my django project through terraform, catch is I need it to be serverless so I need to use Zappa one way or another. So far I've figured I should only use Zappa for zipping up the project for Lambda but I have no idea what else to do. I know I should basically reflect what Zappa does in deployment to terraform but I can't figure out all the things it does. Creates IAM Role Creates Permission Policy Uploads zip to s3, creates lambda Schedules keep_warm callback Uploads Gateway API Settings ? I've got the Gateway API settings in a JSON file but I do not know how to use it for deployment with terraform. What should the lambda handler be in terraform? How do I even do this in terraform? -
How to create a "field group" in django-filter to a searchbar
Good morning, I'm working on a Django site and I'm making a search bar for my site with django-filter library. It's working well but it works only with one model field. I would have a search bar that works with more field (in this case text, desc and title), how is it possible to do? Filters.py import django_filters from django_filters import CharFilter, DateFilter from .models import * class PostFilter(django_filters.FilterSet): text = CharFilter(lookup_expr='icontains') class Meta: model = Post fields = ('text', 'date') Models.py class Post(models.Model): # Post core title = models.CharField(max_length=299) author = models.ForeignKey(User,default=ANONYMOUS_USER_ID, on_delete=models.CASCADE) category = models.CharField(max_length=50) image = models.ImageField(blank=True) desc = models.TextField() text = RichTextField(blank = True, null = True ) date = models.DateTimeField(auto_now=False, auto_now_add=True) slug = models.SlugField(null = True, blank = True, unique=True) Thanks for all. -
html select value from database record in django not working
This question is asked many times, but I think I am having issues with strings in the Django template I have a select tag <select name="category" class="form-control" required="" id="id_category"> <option value="" >--------</option> {% for cat in all_categories %} <option value="{{cat}}" {% if form.instance.category == cat %} selected {% endif %}> {{cat}}</option> {% endfor %} </select> my {{cat}} variable has value 'Django Book' and {{form.instance.category}} also have same value i.e. 'Django Book'. But it doesn't select the desired option however, I am using similar logic in another part <select class="form-control" id="client" required name="client"> <option value=" ">-----</option> {% for customer in all_customers %} <option value="{{customer.pk}}" {% if form.instance.client_id.pk == customer.pk %}selected{% endif %}>{{customer}}</option> {% endfor %} </select> but this time I am comparing ids to select the default option and it works. what is the issue in the above code?? is this issue with strings?? and how can I overcome this. Also, I would like to set strings in the value attribute in the first code example. Thanks for any help. -
Django migration id char column to existing table
I am trying to create an ID charfield column and set it as primary key to an existing table. So because it is an existing table when i generate Migrations django asks me to provide a default value. What can i enter as primary key default for existing rows? If i enter a single string e.x 'abcd' i will get error for existing rows on migrate because of duplicate value -
how fix npm run dev?
Can't configure package.json, this code gives an error: "scripts": { "dev": "webpack --mode development ./leadmanager/frontend/src/index.js --output-path .leadmanager/frontend/static/frontend", "build": "webpack --mode production ./leadmanager/frontend/src/index.js --output-path .leadmanager/frontend/static/frontend" }, When I do npm run dev: (venv) awan2rist@Vladimir lead_manager_react_django % npm run dev > lead_manager_react_django@1.0.0 dev /Users/awan2rist/Dev/lead_manager_react_django > webpack --mode development ./leadmanager/frontend/src/index.js --output-path .leadmanager/frontend/static/frontend sh: webpack: command not found npm ERR! code ELIFECYCLE npm ERR! syscall spawn npm ERR! file sh npm ERR! errno ENOENT npm ERR! lead_manager_react_django@1.0.0 dev: `webpack --mode development ./leadmanager/frontend/src/index.js --output-path .leadmanager/frontend/static/frontend` npm ERR! spawn ENOENT npm ERR! npm ERR! Failed at the lead_manager_react_django@1.0.0 dev script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! /Users/awan2rist/.npm/_logs/2020-11-24T09_20_20_637Z-debug.log -
Question about graphene-django mutation documentation
While I've been able to make my application work, I have some concerns about doing things the right way. Therefore there is something I "do not understand" : In the documentation, here, in the QuestionMutation class, there is a question attribute. What does that actually mean ? It says that it defines the response and I don't understand what this means. Code from the documentation : class QuestionType(DjangoObjectType): class Meta: model = Question class QuestionMutation(graphene.Mutation): class Arguments: # The input arguments for this mutation text = graphene.String(required=True) id = graphene.ID() # The class attributes define the response of the mutation question = graphene.Field(QuestionType) @classmethod def mutate(cls, root, info, text, id): question = Question.objects.get(pk=id) question.text = text question.save() # Notice we return an instance of this mutation return QuestionMutation(question=question) And in my code I've been able to do this : My type : class UserType(DjangoObjectType): class Meta: model = User fields = ( 'id', 'username', 'password', 'email', 'first_name', 'last_name', 'is_active', 'group_ids', ) full_name = graphene.String() # Python property full_identification = graphene.String() # Python property My mutation : class UpdateUser(graphene.Mutation): # --------> I could comment these and no problem. Why ? <-------- # id = graphene.ID() # username = graphene.String() # email …