Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest delete request error "The 'file' attribute has no file associated with it. "
I am using the Django rest framework for the API. I tried to make the file field optional. When I create the instance, it works properly, i.e., I can upload my data without a file. But when I tried to delete it, it shows the following error, The 'file' attribute has no file associated with it. In models.py file, I write as below, file = models.FileField(upload_to="%Y/%m/%d", null=True, blank=True) In serializer.py file, I write as below, class DataSerializer(serializers.ModelSerializer): file = serializers.FileField( required=False, allow_empty_file=True, allow_null=True) class Meta: model = DataIndex fields = '__all__' Can anyone please help me to solve this error? Thanks in advance. -
set command in windows not working for django SECRET_KEY | django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable
I set the SECRET_KEY with set command in the terminal, but nothing works set SECRET_KEY='9l=jjp#g0-mbdfsntqww91s9b^a!kj44ljl4f5h!+uoft' settings.py: from pathlib import Path import environ # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent env = environ.Env( DEBUG=(bool, False) ) READ_DOT_ENV_FILE = env.bool('READ_DOT_ENV_FILE', default=False) if READ_DOT_ENV_FILE: environ.Env.read_env() DEBUG = env('DEBUG') SECRET_KEY = env('SECRET_KEY') ALLOWED_HOSTS = [] .env: SECRET_KEY='9l=jjp#g0-mbdfsntqww91s9b^a!kj44ljl4f5h!+uoft' DEBUG=True So as you can read, the READ_DOT_ENV_FILE should be True to let django read the system variables from .env file, otherwise, it'll read the variables from the terminal (session) by defining them in it using the set command. In this case: set DEBUG=True set SECRET_KEY='9l=jjp#g0-mbdfsntqww91s9b^a!kj44ljl4f5h!+uoft' -
How to format index pagination url format django
Question is really similar to Django sitemap index pagination URL format but i didn't get the answer. So, i need my url to be like this /sitemap-products-3.xml, where 3 is page by paginator. My current working links: sitemap-products.xml?p=3 . It's was generated by generic function (index). I did some work, and links look like sitemap-products-3.xml , but in urls.py, I don't know how to pass number of page in paginator, cuz the link gives me 404. Thats my sitemap.xml (index func) def index(request, sitemaps, template_name='sitemap_index.xml', content_type='application/xml', sitemap_url_name='django.contrib.sitemaps.views.sitemap'): req_protocol = request.scheme req_site = get_current_site(request) sitemaps_lastmod = [] sites = [] # all sections' sitemap URLs for section, site in sitemaps.items(): # For each section label, add links of all pages of its sitemap if callable(site): site = site() protocol = req_protocol if site.protocol is None else site.protocol sitemap_url = reverse(sitemap_url_name, kwargs={'section': section}) absolute_url = '%s://%s%s' % (protocol, req_site.domain, sitemap_url) sites.append(absolute_url) sitemaps_lastmod.append(sitemaps[section].index_lastmod(sitemaps[section])) # Add links to all pages of the sitemap. for page in range(2, site.paginator.num_pages + 1): absolute_url = absolute_url.strip('.xml') sites.append('%s-%s.xml' % (absolute_url, page)) if len(sites) > len(sitemaps_lastmod): for x in range(len(sites)-len(sitemaps_lastmod)): sitemaps_lastmod.append(sitemaps[section].index_lastmod(sitemaps[section])) sitez = zip(sites, sitemaps_lastmod) return render(request, template_name, {'sitemaps': sitez}, content_type=content_type) and urls.py: path('sitemap.xml', sitemaps.index, {'sitemaps': sitemaps_pages}), path('sitemap-<section>.xml', sitemap, … -
How to fix this Openedx-Error : str has no attribute id
Hello I've recently upgraded openedx from Hawthorn -> Koa The procedure is : Hawthorn -> Ironwood -> Juniper -> Koa There is no error in migrating but as I was logging in, this error occurs: File "/edx/app/edxapp/venvs/edxapp/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/edx/app/edxapp/venvs/edxapp/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/edx/app/edxapp/venvs/edxapp/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python3.8/contextlib.py", line 75, in inner return func(*args, **kwds) File "/edx/app/edxapp/venvs/edxapp/lib/python3.8/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/edx/app/edxapp/venvs/edxapp/lib/python3.8/site-packages/django/utils/decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "/edx/app/edxapp/edx-platform/openedx/core/djangoapps/util/maintenance_banner.py", line 42, in _decorated return func(request, *args, **kwargs) File "/edx/app/edxapp/edx-platform/common/djangoapps/student/views/dashboard.py", line 830, in student_dashboard return render_to_response('dashboard.html', context) File "/edx/app/edxapp/edx-platform/common/djangoapps/edxmako/shortcuts.py", line 193, in render_to_response return HttpResponse(render_to_string(template_name, dictionary, namespace, request), **kwargs) File "/edx/app/edxapp/edx-platform/common/djangoapps/edxmako/shortcuts.py", line 183, in render_to_string return template.render(dictionary, request) File "/edx/app/edxapp/edx-platform/common/djangoapps/edxmako/template.py", line 83, in render return self.mako_template.render_unicode(**context_dictionary) File "/edx/app/edxapp/venvs/edxapp/lib/python3.8/site-packages/mako/template.py", line 481, in render_unicode return runtime._render( File "/edx/app/edxapp/venvs/edxapp/lib/python3.8/site-packages/mako/runtime.py", line 878, in _render _render_context( File "/edx/app/edxapp/venvs/edxapp/lib/python3.8/site-packages/mako/runtime.py", line 920, in _render_context _exec_template(inherit, lclcontext, args=args, kwargs=kwargs) File "/edx/app/edxapp/venvs/edxapp/lib/python3.8/site-packages/mako/runtime.py", line 947, in exec_template callable(context, *args, **kwargs) File "/tmp/mako_lms/c4ececd1e3f991d50ac3b7742d7479be/my-bootstrap/lms/templates/main.html.py", line 331, in render_body runtime._include_file(context, (static.get_template_path('header.html')), _template_uri, online_help_token=online_help_token) File "/edx/app/edxapp/venvs/edxapp/lib/python3.8/site-packages/mako/runtime.py", line 795, in include_file callable(ctx, **kwargs) File "/tmp/mako_lms/c4ececd1e3f991d50ac3b7742d7479be/header.html.py", line 34, in … -
Django how to properly add validation error message in views
I am trying to add validation in my views but error message not showing in my template. I am getting this page if user enter wrong input: views.py from django import forms from django.core.exceptions import ValidationError if request.method == "POST": if comment_form.is_valid(): if request.POST['name'] != username: raise forms.ValidationError('inc') -
could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432?
I have a server running well on digital ocean but suddenly one error came as "" I am using nginx and gunicorn to server the application. It was running well but suddenly error appeared. I also did not make any change in application. Also this is what I am seeing when I write the command systemctl status postgresql -
How to have shared related name?
I am trying to create a model to represent travel time between two venues, so it has two foreign keys to the Venue model: class VenueTravel(models.Model): venue1 = models.ForeignKey('Venue', related_name='travel_times') venue2 = models.ForeignKey('Venue', related_name='travel_times') minutes = models.IntegerField(default=0, validators=[MinValueValidator(0)]) class Meta: unique_together = ('venue1', 'venue2') However, I'm having trouble making the migration for this model because the related name clashes for both fields. Usually, I would understand why, but since in this case the related object relation back to this object represents the same for both fields (all travel distances for the venue, no matter if it's venue1 of venue2), I don't really care about naming them differently. In fact, I'd want to name them the same. Is there any way I could do that? If you think there's a better way of modelling this use case, please feel free to make your suggestion. -
Using arguments to nested structures for filtering parents using django-graphene
I'm currently using Python & Django with Graphene to model my Graphql backend. My question is similar to this one on Graphene's repo https://github.com/graphql-python/graphene/issues/431. I'm also using graphene_django_optimizer library to improve performance. However I'm having a hard time understanding how to apply @syrusakbary proposed solution to my problem in my current scenario. Any help would be much appreciated This is the query I wanna execute getUser(userId: $userId) { id username trainings{ id name sessions{ id createdAt completedAt category } } } } The trainings are brought correctly, only the ones belonging to that specific user id. However all sessions for each training are brought for all users. I'd like sessions to also be specific to that single user. Here on my types.py are the relevant types class SessionType(DjangoObjectType): class Meta: model = Session fields = "__all__" convert_choices_to_enum = False @classmethod def get_queryset(cls, queryset, info, **kwargs): if info.context.user.is_anonymous: return queryset.order_by('-id') return queryset class TrainingType(gql_optimizer.OptimizedDjangoObjectType): class Meta: model = Training fields = "__all__" convert_choices_to_enum = False class UserType(DjangoObjectType): class Meta: model = get_user_model() fields = "__all__" Here are my relevant models: class Training(models.Model): name = models.CharField(max_length=200, help_text='Training\'s name') details = models.TextField(default="", help_text='Descriptive details about the training') course = models.ForeignKey("Course", related_name="trainings", on_delete=models.CASCADE) user … -
Chart.JS Datasets not showing in Django Project
I have a chart made with chart.JS on one of my django pages that is working perfectly. I tried to replicate it on another page with different data, and I can't seem to get the data points to show. The x axis labels show fine, but the y axis data sets aren't showing despite having the proper data set. <div class="chart-container"> <canvas id="annualChart"></canvas> <script> function toggleData(value){ const showValue = annualChart.isDatasetVisible(value); if(showValue === true) { annualChart.hide(value) } if(showValue === false) { annualChart.show(value) } } var years2 = {{annual_income.date|safe}} var revenue2 = {{annual_income.revenue|safe}} var grossProfit = {{annual_income.grossProfit|safe}} var researchAndDevelopment = {{annual_income.researchAndDevelopmentExpenses|safe}} var ctx = document.getElementById('annualChart'); var annualChart = new Chart(ctx, { type: 'line', // OPTIONS options: { maintainAspectRatio: false, plugins: { legend: { onClick: null, display: true, labels: { filter: function(item, annualChart) { return !item.hidden; } } }, }, scales: { yAxes: [{ stacked: true, gridLines: { display: true, color: "rgba(255,99,132,0.2)" } }], xAxes: [{ gridLines: { display: false } }] } }, // Data data: { labels: years2, datasets: [{ label: 'Revenue', data: revenue2, backgroundColor: 'rgba(255, 99, 132, 0.2)', borderColor: 'rgba(255, 99, 132, 1)', borderWidth: 1 }, { label: 'Gross Profit', data: grossProfit, backgroundColor: 'rgba(54, 162, 235, 0.2)', borderColor: 'rgba(54, 162, … -
Ignore `is_active` filed for custom user model
This is my custom user model: from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ class MyUser(AbstractUser): username = None is_staff = None is_superuser = None is_active = None email = models.EmailField(_('email address'), unique=True) status = models.PositiveSmallIntegerField(default=0) In settings.py file added: AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.AllowAllUsersModelBackend'] Then, when trying to login, getting error: This account is inactive. How to ignore is_active filed for my custom user model ? -
Disable public to download files like .env
How to disable download files in the root folder? For example when I go to the link; https://example.com/.env It will download the .env file, and https://example.com/projectfolder/settings.py It will download the settings.py file. How can I disable the download access? Thank you. -
Getting Error when trying to save Django Model to My Sql Dtatabase
Hi I'm getting this error when I try to save a model AttributeError: 'tuple' object has no attribute 'startswith. Basicly the program should show a list of all users. But even though in the table there are already some entries. The table I show on the Web side is empty and no error is shown. models.py: from django.db import models from django.db import connections class Users(models.Model): identifier = models.CharField(primary_key=True,max_length=100) accounts = models.TextField() group = models.CharField(max_length=100) inventory = models.TextField() job = models.CharField(max_length=100) job_grade = models.IntegerField() loadout = models.TextField() position = models.CharField(max_length=300) firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) dateofbirth = models.CharField(max_length=100) sex = models.CharField(max_length=100) height = models.IntegerField() skin = models.TextField() status = models.TextField() is_dead = models.SmallIntegerField() phone_number = models.CharField(max_length=100) class Meta: db_table = "users", views.py from django.shortcuts import render from .models import Users # Create your views here. def show(request): newUser = Users( identifier = "abc", accounts = "[]", group = "admin", inventory = "[]", job = "police", job_grade = 3, loadout ="[]", position = "da", firstname = "swpw", lastname = "wwww", dateofbirth = "wolplwodokwowdüp", sex = "m", height = 78, skin = "[]", status = "[]", is_dead = 0, phone_number = "hallo",) newUser.save() return render(request,'acp/show.html',{'user':users}) -
I get error messages at terminal when I try to run manage.py runserver
I get error messages whenever I try to run manage.py, ModuleNotFoundError: No module named 'PyShop.settings', but I have this module, named "PyShop.settings" in my folder. C:\Users\uer\PycharmProjects\PyShop>python manage.py runserver Traceback (most recent call last): ... ModuleNotFoundError: No module named 'PyShop.settings' -
YAML text editor field in Django
I am looking for a convenient way to write and edit YAML in Django admin panel. Are there any text editors in django admin panel for YAML -
How to implement method from Model to form
I have in my models.py method of Model: class Book(model.models): ... def generate_tag(self): return f'{self.inspection.series_of_tags}-{str(self.tag_number).zfill(7)}' I want to implement this method in my form when I push on update view it generate new tag: class TagForm(core.ModelForm): def save(self, commit=True): instance = super().save(commit=False) if self.cleaned_data['tag_number']: instance = Book.generate_tag(self.instance) if commit: instance.save() return instance class Meta: model = Book fields = ( 'tag_number', ) my views.py class BookUpdateView(BookViewMixin, core.UpdateView): form_class = TagForm template_name = 'book.html' I want that when I click update view - my field 'tag number' will give method from model 'generate_tag' when I save my Form!What I am doing wrong in my code? -
Need help creating search view and how to apply in the HTML page from DB that I created - Django
I am building a website with DJANGO where people put words and association how to remember the word. I built the part of inserting the word. I am now stuck in the part of implementing the word search and extracting the information from the DB. def Search_word(request): search = request.POST.get("search", False) if search in Words.English_word: return HttpResponseRedirect("/polls/") else: return HttpResponseRedirect("/polls/") -
Problems with using built-in postgres database with Django
I'm trying to use built-in postgres database with django according to the instruction: https://docs.djangoproject.com/en/3.2/ref/databases/#postgresql-notes When running the server I get the error: django.db.utils.OperationalError: fe_sendauth: no password supplied How should I define the database credentials in this case (I'm expecting that the build-in database is just created at server startup, thus I could give any...)? I've also been trying to use postgres database running in a docker container. I got the same error though I think I was using the correct credentials: docker pull postgres docker run -e POSTGRES_PASSWORD=pw -e POSTGRES_USER=pg -d postgres and my django settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'pg', 'USER': 'pg', 'PASSWORD': 'pw', 'HOST': '127.0.0.1', 'PORT': '5432', 'TEST': { 'NAME': 'mytestdatabase', } } } python manage.py runserver 8030 ... conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: FATAL: password authentication failed for user "pg" -
Django, Foreign key not getting filled with session data
im trying to fill my foreignkey (employer) with the user that is logged in, but i have seen alot of way but they havent worked for me, does anyone know what im doing wrong? and how i can fix it? View: class JobCreate(CreateView): model = Job form = JobCreateForm() form_class = JobCreateForm context = {} success_url = reverse_lazy('jobsview') def POST(self,request): if request.method == 'POST': form = JobCreateForm(request.POST) if form.is_valid(): job = form.save(commit=False) job.employer = request.user job.save() context = {} return render(request, 'jobs/jobs.html',context) else: context = {} return render(request, 'jobs/job_form.html',context) Model: class Job(models.Model): employer = models.ForeignKey(User, related_name='employer', on_delete=CASCADE,blank=True) employees = models.ManyToManyField(User, related_name='employees2user',null=True,blank=True) title = models.CharField(max_length=200,) description = models.CharField(max_length=200,null=True,blank=True) category_id = models.ManyToManyField(Category,blank=True) skill_id = models.ManyToManyField(Skill,blank=True) approved = models.BooleanField(default=False) # img = models.ImageField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): # Default value return self.title HTML: {% extends "jobs/layout.html" %} {% block content %} <h3> Job</h3> <div class="container"> <div class="jobform"> <form action="" method="POST"> {%csrf_token%} {% for field in form %} <label for="{{field.id_for_label}}">{{field.html_name}}</label> {{field}} {% endfor %} <p>Ctrl in houden om meerder te selecteren</p> <button type="submit" class="btn btn-dark btn-space">Submit</button> </form> </div> </div> {%endblock%} -
Getting error when trying run test “RuntimeError” Database access not allowed
I have some celery tasks running in my project. I want to write some tests for tasks using pytest factories. But each time i pass a task to my test i give me error Getting error when trying run test “RuntimeError” Database access not allowed. Here is code example def send_orders(): for order in Order.objects.all(): order.send() order.sent = True class OrderFactory(....): amount = 100 sent = False def test_send_orders(order): send_orders() assert order.sent -
While using Redirect in django , Login required decorator is not working
view.py @login_required def Loginup(request): if request.method == 'POST': regex = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$' email = request.POST.get('email') password = request.POST.get('password') bad_chars = "!#$%^&*()[]{'}-+?_=,<>/" parameters = [email, password] filtered_parameters = [] for i in parameters: a = ''.join(c for c in i if c not in bad_chars) filtered_parameters.append(a) checking = Client.objects.all().filter(Email=filtered_parameters[0]) checking1 = authenticate(request, Email=email, Password=password) pop = ([i for i in checking.iterator()]) for enc in checking: value = D256(filtered_parameters[1], enc.Password) if value != False: for check in checking: request.session['id'] = check.id request.session['email'] = check.Email # REDIRECT >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> response = redirect('/home/%s' % encrypt(check.id)) set_cookie(response, check.Name, check.Password) response.set_cookie( 'echo-AI', [check.Email, check.Password]) return response else: messages.success(request, 'check the details') return redirect('login/') return render(request, 'login.html') setting.py: LOGIN_URL = 'supers:login' url.py(app): from django.urls import path from supers import views app_name = 'supers' urlpatterns = [ path('', views.Index, name='index'), path('signup/', views.Signup, name='signup'), path('login/', views.Loginup,name='login'), path('home/<str:id>',views.Home,name='home'),] url before useing @login required: http://127.0.0.1:8000/home/Z0FBQUFBQmhFWFJBRVdnLWxUNHRKeFNhaWZPYi1oN3hQUVF5cE5CSTRIbTdMZkdUcXFlbFNYeFl0alB3ZGtvSFVKcDVDRnQ0UkRCdWxrMkFSVGxYUG5FVWF1V2t3MU5JdEE9PQ== url after useing @login required: http://127.0.0.1:8000/login/?login/=/home/Z0FBQUFBQmhFWFBNM2JWUXhIdzRwTWdWcDVUYUZMZ191WGg3OG5OUE9YaEFOaDdLeF9zR1FEODYtM3p0Zlh0VjlobWoyMmlycmphY0lXdDdGNDRYUEZtMVhkOHA1TXowc0E9PQ%253D%253D so i tried a example project : (its woring while using render) def Login(request): if request.method == 'POST': email = request.POST.get('email') password = request.POST.get('password') print('User1:::::::::::::::::::::::::::::::', email) print('User2:::::::::::::::::::::::::::::::', password) data = Client.objects.filter(Email=email, Password=password) if data: return render(request, 'home.html') return render(request, 'login.html') return render(request, 'login.html') @login_required def Home(request): return render(request, 'home.html') @csrf_exempt def Logout(request): … -
Same datetime being saved in different Drf endpoint calls
I'm using datetime.now() and somehow the same date and time up to the second is being saved on my postgre db on different api calls. This would occur for around 5+ times a few minutes apart before changing to another date. What could be causing this? I have this up on a remote Dev server with nginx and uwsgi. For now, i'm saving the record then getting the updated_at value (which is always correct). I'm using the following settings. I've also tried timezone.now(). In addition to the problem above, i've noticed that the datetime i get is a hours early (datetime.now()) or minutes early (timezone.now()). On my local machine, this problem doesn't seem to occur. Any help would be appreciated. Thanks! LANGUAGE_CODE = 'en-us' USE_I18N = False USE_L10N = False USE_TZ = True TIME_ZONE = 'Asia/Manila' -
how to add non existing language to my django website - invalid token in plural form
i'm trying to add (kurdish) language to my django app , but settings.LANGUAGES doesnt support kurdish (ku) code , i also tried to use rosetta ( ROSETTA_LANGUAGES ) which have kurdish in their languages website list , but it also not show in my template <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> languages </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for lang in languages %} <li> <a class="dropdown-item" href="/{{lang.code}}/"> {{lang.name_local}}</a> </li> {% endfor %} </ul> </li> and this is my settings.py from django.conf import global_settings import django.conf.locale from django.utils.translation import gettext_lazy as _ LANGUAGE_CODE = 'ku' #ROSETTA_LANGUAGES = ( # ('en',_('english')), # ('ar',_('arabic')), # ('ku',_('kurdish')) #) LANGUAGES = ( ('en',_('english')), ('ar',_('arabic')), ('ku',_('kurdish')) ) ROSETTA_WSGI_AUTO_RELOAD = True EXTRA_LANG_INFO = { 'ku': { 'bidi': True, # right-to-left 'code': 'ku', 'name': 'Kurdish', 'name_local': u'\u0626\u06C7\u064A\u063A\u06C7\u0631 \u062A\u0649\u0644\u0649', LANG_INFO = dict(django.conf.locale.LANG_INFO, **EXTRA_LANG_INFO) django.conf.locale.LANG_INFO = LANG_INFO # Languages using BiDi (right-to-left) layout LANGUAGES_BIDI = global_settings.LANGUAGES_BIDI + ["ku","kurdish"] LOCALE_PATHS = ( os.path.join(BASE_DIR,'locale/'), ) is there something else i have to add to the settings please ? thanks in advance .. -
Django migration passed but field did not get deleted
I have a django application in production, last week I wanted to delete a field from my user model, review_rate, to replace it by a M2M relation with another table. The resulting migration is: # Generated by Django 2.2.1 on 2021-07-20 16:41 import django.db.models.deletion from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0080_auto_20210708_1539'), ] operations = [ migrations.SeparateDatabaseAndState(state_operations=[ migrations.CreateModel( name='Rate', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], options={ 'db_table': 'api_project_reviewers', }, ), migrations.RemoveField( model_name='user', name='review_rate', ), migrations.AlterField( model_name='project', name='reviewers', field=models.ManyToManyField(related_name='review_project', through='api.Rate', to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='rate', name='project', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.Project'), ), migrations.AddField( model_name='rate', name='user', field=models.ForeignKey(limit_choices_to={'reviewer': True}, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), ]) ] It works fine locally. When I deploy it, I can see that my migration exists and pass with the showmigrations command, however, when I want to add a user I get this exception: null value in column "review_rate" violates not-null constrain. If I go to my container, choose any user and try to get review_rate on it I get this error as expected: AttributeError: 'User' object has no attribute 'review_rate' SO the review_rate field does not seem to be deleted as it should, BUT my new rate field exists.. Could someone explain how to … -
How to combine two Model fields to get a common json data in DJANGO?
I'm new to DJANGO , I am trying to combine three models to get a common listing. What i have done is it will get JSON result for each models from database based on the URL given. Eg: Model1 having fields like id,name,date Model2 having fields like id,name,date Now im getting result for these two models are like for Model1 `{ "id": "1", "name": "test", "date": "9-Aug-2021" }` similarly Model2 also. I'm done this with rest-api for Django. Now i want to combine these two models to get a common result. How can we do this in django. -
How to get data from dynamic html table in django.?
I have table with 3 columns and rows will be added dynamically depending on of subjects count. 1column is label and others 2 are input fields. How would I get table data after post, into views.py function ? Html table <form method="POST" action= "{% url 'save_report' %}"> {% csrf_token %} <table id="myTable"> <tr> <th> SUBJECTS </th> <th> Full Marks</th> <th> Marks OBTAINED</th> </tr> {% for subject in subjects %} <tr> <td> <label type="text" id="a" name="a"> {{subject.subject_name}}</label></td> <td> <input type="number" id="b" name="b"/></td> <td> <input type="number" id="c" name="c"/></td> </tr> {% endfor %} <button type="submit" onclick= "{% url 'message_page' %}" name="save" id="save">save </button> My views.py def save_report(request): if request.method=="POST": Full_marks= request.POST.get("b") Print(Full_marks) #check Obtained= request.POST.get("c") Print(Obtained) #check else: Do Stuff Here in save_report() function in views.py I'm getting only last entered value of the input field. I'm trying to save table inputs into database as it is. Any guidance is appreciated. Please..