Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Unknown column 'pm' in 'weather_weather'
I have a Django project, connecting to database use mariadb And I used pm Field first . However, I changed pm Field into rainfall in models.py. | Field | Type | Null | Key | Default | Extra | +-------------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | time | datetime | NO | | NULL | | | temperature | decimal(3,1) | YES | | NULL | | | humidity | decimal(3,1) | YES | | NULL | | | uv | int(11) | YES | | NULL | | | light | int(11) | YES | | NULL | | | rainfall | int(11) | YES | | NULL | | This is my 4th migrations file This is my 3th migration file Why? -
add custom field to each object in ListView
I am trying to add a custom field to a ListView to describe an entity more verbose-ly (so that I can then use it in the template) but surprisingly cant find a straight forward way to do that. How can I add context to each object in the list? self.object_list returns the whole list and it feels counter-intuitive to iterate through it to add this extra field. class AreaWiseSchoolsView(ListView): template_name = 'search/area.html' paginate_by = 15 def get_queryset(self): qs = School.objects.filter(area__name=self.kwargs['areaname']) return qs def get_context_data(self, **kwargs): school_type_description = "" context = super(AreaWiseSchoolsView, self).get_context_data(**kwargs) # school = self.something # need code here to get the current list # if qs.area.filter(pk=9).exists(): # school_type_description = "Some description for Area 9" if qs.school_type == 'ND': school_type_description = "Some description for ND" elif qs.school_type == 'MA': org_type_description = "Some description for MA" context['school_type_description'] = school_type_description return context Also, is there a simpler way to do the above instead of overriding get_context_data()? -
jinja2 groupby choice field
In my Django model I have choice field MY_GROUPS = [ ('GR1', 'First Group'), ('GR2', 'Second Group) ] class MyModel(models.Model): ... group = models.CharField(choices=MY_GROUPS, max_length=3) Now I use groupby filter to display my queryset as it is explained in jinja2 docs <ul> {% for group in persons|groupby('group') %} <li>{{ group.grouper }}<ul> {% for person in group.list %} <li>{{ person.first_name }} {{ person.last_name }}</li> {% endfor %}</ul></li> {% endfor %} </ul> But {{ group.grouper }} is a string which is field value: GR1, GR2 . How can i get my field display name as grouper string: First Group, Second Group -
django heroku run ETIMEDOUT, Application Error
I made a django project using channels. And I want to deploy it. Because my project uses channels, I need to set up ASGI based environment. I pushed my project and succeeded.So I got URL address. demo-multichat.herokuapp.com When you connect above url, Application error page is shown. And I faced another problem. In my local terminal, when I executed $ heroku run python manage.py migrate I got ETIMEDOUT error. please refer to below picture. Before migrate I stoped and started local redis server. But end up failing migrate. how can I resolve these issues? I want to migrate and eventually connect my web service. p.s.) I read an article. Let me attach link. Hopefully that article have some hints, clues. p.s.) My Development Environment : Ubuntu 16.04 / 64bit / My laptop is connected to university wireless network(WIFI) -
Sphinx with Django - Model doesn't declare an explicit app label
I have spent countless hours but this is still stuck. The documentation is so lacking. Using Django 1.10, trying to create Sphinx documentation which has been giving various errors. Finally I am stuck here. I created an example model in my main app kyc_connect as below. Models.py from django.db import models class example(models.Model): filed1 = models.DateTimeField(auto_now=True) field2 = models.CharField() # class Meta: # app_label = 'kyc_connect' Running make_html gives the below error. RuntimeError: Model class kyc_connect.models.example doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Conf.py import settings import os import sys sys.path.insert(0, os.path.abspath('..')) from django.conf import settings settings.configure() import django django.setup() When I include Meta class presently commented out, this errors goes away. But if I include a model with ForeignKey and import from django.contrib.auth.models import User it gives error RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. INSTALLED_APPS INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework_swagger', 'rest_framework', 'rest_framework.authtoken', 'kyc_connect', 'kyc_connect_data_models', 'kyc_rest_services.kyc_connect_accounts', 'kyc_rest_services.kyc_connect_documents', 'kyc_rest_services.kyc_connect_transaction_manager', 'tasks', 'elasticstack', 'corsheaders', 'haystack' ] ProjectStructure kyc_connect: -config -docs -kyc_connect -models.py . . -kyc_connect_data_models -kyc_core -kyc_rest_services -kyc_connect_accounts -kyc_connect_transaction_manager . . . . I already have django.contrib.contentype there. But django doesn't seem to … -
Cannot chmod file on Openshift online v3 : Operation not permitted
I am migrating a Django application from Openshift v2 to v3 (In case you don't know, RedHat is shutting down v2 on September 30th, see: https://blog.openshift.com/migrate-to-v3-v2-eol/) So, I am following this blog post to help me: https://blog.openshift.com/migrating-django-applications-openshift-3/ . I am new to all these Docker / Kubernetes concepts the new version is build upon. I was able to make some progress : I managed to get a successful build of my app. Yet it crashes at deployment time: ---> Running application from script (app.sh) ... /usr/libexec/s2i/run: line 42: /opt/app-root/src/app.sh: Permission denied Indeed, app.sh has lost its x permission. I log into the failing container as debug and see it: > oc debug dc/<my app> > (app-root)sh-4.2$ ls -l /opt/app-root/src/app.sh -rw-rw-r--. 1 default root 127 Sep 6 21:20 /opt/app-root/src/app.sh The blog posts states "Ensure that the app.sh file is executable by running chmod +x app.sh.", which I did on my local repo. Whatever, I want to do it again directly in the pod, but it doesn't work: (app-root)sh-4.2$ chmod +x /opt/app-root/src/app.sh chmod: changing permissions of ‘/opt/app-root/src/app.sh’: Operation not permitted So, how can I set the x permission to app.sh ? Thank you -
How can I get user_id in separated place?
I wanna parse excel& make dictionary and connect the model(User) which has same user_id of dictionary. Excel is user_id is in F1,so I really cannot understand how to make dictionary. Now views.py is #coding:utf-8 from django.shortcuts import render import xlrd from .models import User book = xlrd.open_workbook('../data/excel1.xlsx') sheet = book.sheet_by_index(1) def build_employee(employee): if employee == 'leader': return 'l' if employee == 'manager': return 'm' if employee == 'others': return 'o' for row_index in range(sheet.nrows): rows = sheet.row_values(row_index) is_man = rows[4] != "" emp = build_employee(rows[5]) user = User(user_id=rows[1], name_id=rows[2], name=rows[3], age=rows[4],man=is_man,employee=emp) user.save() book2 = xlrd.open_workbook('../data/excel2.xlsx') sheet2 = book2.sheet_by_index(0) headers = sheet2.row_values(0) large_item = None data_dict = {} for row_index in range(sheet2.nrows): rows2 = sheet2.row_values(row_index) large_item = rows2[1] or large_item # Create dict with headers and row values row_data = {} for idx_col, value in enumerate(rows2): header_value = headers[idx_col] # Avoid to add empty column. A column in your example if header_value: row_data[headers[idx_col]] = value # Add row_data to your data_dict with data_dict[row_index] = row_data for row_number, row_data in data_dict.items(): user1 = User.objects.filter(user_id = data['user_id']).exists() if user1: user1.__dict__.update(**data_dict) user1.save() My codes only can catch data in same place(in this case B4~E4),so I cannot understand how to write to achieve my goal.How … -
Django Invitation app link to other models
) I am trying to I am trying to install and configure an external app that allow to send mail invitation (https://github.com/bee-keeper/django-invitations). My goal is to be able invite team Members to join as a team my app by sending them mails invitation to join the app. I managed (with help) to make it work and send email, the thing is I would like now those mail to be attached to another model which is the team model and create a new team. The thing is up-until the team member sign-in there are not users of my app ... so I have no idea how to make it work .. here is my views.py from django.shortcuts import render from django.views.generic import TemplateView from .forms import InviteForm from invitations.models import Invitation def create_invite(request): if request.method == "POST": invite_form = InviteForm(data=request.POST) if invite_form.is_valid(): email1 = invite_form.cleaned_data['email1'] email2 = invite_form.cleaned_data['email2'] email3 = invite_form.cleaned_data['email3'] email4 = invite_form.cleaned_data['email4'] email5 = invite_form.cleaned_data['email5'] for i in invite_form.cleaned_data: invite = Invitation.create(i) invite.send_invitation(request) print("The mail was went") else: print("Your form is not valid") else: invite_form = InviteForm() return render(request, 'HRIndex.html', {'invite_form': invite_form}) This is my model.py from django.db import models class Team(models.Model): team_name = models.CharField(max_length=150) class TeamMembers(models.Model): team = … -
H27 - Client Request Interrupted
I am getting H27 warnings in heroku for a django based app, for requests possibly requiring long running processing. The strange thing is, the request doesn't fail but appears to be executed twice. I.e. if my request should create one object, I get two objects instead. Looking at the logs it looks like the request is starting again just after the warning is emitted. The first warning happens about 10 seconds after the start of the initial request. Those request are post requests coming from an ios app. Is this to be expected? Where should I be looking to debug this? (on top of that, I can't really reproduce, but it seems to happen from time to time). -
How I access the string from url in middleware
How I access the url parameter in my middleware Here is my urls.py from django.conf.urls import include, url from django.contrib import admin from views import * urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^my_url/(?P<string>[\w\-]+)/$', my_view), ] Now I want to access the string vale in my middleware. Here is my middle ware code class MyMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Here I want a string variable value Is there any solution to access the value of string variable -
Hide header and entire column when the value is equal to null. Python and Django
I've tried to google how to solve this problem. But most of it was not related to this. This program is to get input from user, which is in checkbox format, it will read all the content in text file and display it in table format on website. QUESTION Any possible command that the column only will be display if the column has value?? Note : If you understand and saw this problem before please post the link here. THIS IS MY TEXT FILE `delay_index_time 775435 id 7754764 delay_index_time 456345 id 64564 delay_index_time 4567867867868 id 3453454 delay_index_time 567867` views.py tokens = request.GET.getlist('token') # ... with open(path) as input_data: for line in input_data: if 'visual' in tokens and line.startswith('id_'): prev_key = line.lstrip('id_').rstrip() data.update({prev_key: []}) # you may want to continue to next line here - or not # continue if 'time' in tokens: if search_string in line and prev_key in data: data[prev_key].append(next(input_data).rstrip()) else: if search_string in line: prev_key = (next(input_data).rstrip()) data.update({prev_key:[]}) context = {'output': data,} html table <div class="input-group" align="center" style=" left:10px; top:-110px; width:99%"> <table class="table table-bordered"> <thead class="success" > <tr> <th class="success"> <b>Visual ID</b> </th> <th class="success"> <b>Time Delay Index Time</b> </th> </tr> {% for key, values in output.items %} … -
Django ORM Filter By Checking Both column contains same values
I have a model contains 3 column as follows: Id NoOfL2 Open Delete Inprogress 1 2 1 1 0 2 4 1 2 1 3 3 3 0 0 I want to fetch all rows contains NoOfL2 == Open. How should I found it using Django ORM? -
RuntimeWarning: DateTimeField myTable.test received a naive datetime
trying to send some records into my database. I am sending date in the following format: 2017-08-06 00:41:58 But receiving the message : RuntimeWarning: DateTimeField myTable.test received a naive datetime (2017-08-06 00:41:58) while time zone support is active. Records are saving correctly ,but why am I see this message ? Thanks in advance, -
TypeError: 'int' object is not subscriptable Where is int?
I got an error,TypeError: 'int' object is not subscriptable . I wanna connect 2 excel data to User model. So my ideal output is 1|1|Blear|40|false|l|America|A|1 2|5|Tom|23|true|o|UK|A|3 3|9|Rose|52|false|m 4|10|Karen||||Singapore|C|2 For example,Rose data of user_id=3 is not in second excel, in that case being 2nd data empty is ok.I am thinking putting 2nd excel in dictionary type to User model. views.py is #coding:utf-8 from django.shortcuts import render import xlrd from .models import User book = xlrd.open_workbook('../data/excel1.xlsx') sheet = book.sheet_by_index(1) def build_employee(employee): if employee == 'leader': return 'l' if employee == 'manager': return 'm' if employee == 'others': return 'o' for row_index in range(sheet.nrows): rows = sheet.row_values(row_index) is_man = rows[4] != "" emp = build_employee(rows[5]) user = User(user_id=rows[1], name_id=rows[2], name=rows[3], age=rows[4],man=is_man,employee=emp) user.save() book2 = xlrd.open_workbook('../data/excel2.xlsx') sheet2 = book2.sheet_by_index(0) headers = sheet2.row_values(0) large_item = None data_dict = {} for row_index in range(sheet2.nrows): rows2 = sheet2.row_values(row_index) large_item = rows2[1] or large_item # Create dict with headers and row values row_data = {} for idx_col, value in enumerate(rows2): header_value = headers[idx_col] # Avoid to add empty column. A column in your example if header_value: row_data[headers[idx_col]] = value # Add row_data to your data_dict with data_dict[row_index] = row_data for data in data_dict: user1 = User.objects.filter(user_id = data['user_id']).exists() … -
What's the relation of db tables, models and serializers in Django REST?
I am confused about the function of serializers in Django REST Framework. It is said in official document, Serializers: Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data. So in my understand, they have a relation like this: database table <--> model instance(queryset) <--> serializer <--> native Python datatypes(dict, list) <--> JSON/XML Is it right?? -
Django Admin, show one field values in two separate horizontal multichoices
I am new to Python Django and I cannot find solution to one of tasks assigned to me, although I have done a lot of research. I have two models: class Model1(AbstractModel): name = models.CharField(max_length=255) parent = models.ForeignKey('self', null=True, blank=True) class Model2(AbstractModel): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100, blank=True) email = models.EmailField(max_length=255, blank=True) phone_number = models.CharField(max_length=100, blank=True) model1 = models.ManyToManyField(Model1, blank=True) timezone = models.CharField(max_length=300, choices=TIMEZONE_CHOICES, null=True, blank=True) Model1 is internally having a relation of parent child. If any Model1 is having parent value it is considered as type Child else it's a Parent. Now, my requirement is to show two separate selection lists instead of one for Model1 field as Model1-Parent and Model1-Child on Django Admin portal and the selection result of both should save in the actual field which is Model1. I tried to search for the solution and I found you can create ModelForm to achieve that. I am not sure the problem will be solved with ModelForm or not so any guidance will be really helpful for me before jumping into actual implementation. If anyone has another approach or recommendation on what is the best way to do this, please provide me some example for that. -
POST method of FormView in Django?
I am tring to understand how works Class Based Views in Django. I have next working code with View. I want to write that code with the help of FormView. Is my `FormView code correct? I need someone who can analyze that code and say where is my mistakes. I would be grateful for any help. Right now get method works. The problem is when I try to submit form. Form dont disappear. In the same time in console I see this url: "POST /url/ HTTP/1.1" 200 1891. In database I see that new article was created. How to fix this strange problem with post method? CBV with View: class ArticleCreateView(FormView): template_name = 'article/create_article.html' form_class = ArticleForm def post(self, request): data = dict() article_create_form = ArticleForm(request.POST, request.FILES) if article_create_form.is_valid(): article_create_form.save() data['form_is_valid'] = True context = { 'articles': Article.objects.all() } data['html_articles'] = render_to_string( 'article/articles.html', context ) else: data['form_is_valid'] = False return JsonResponse(data) def get(self, request): data = dict() article_create_form = ArticleForm() context = { 'article_create_form': article_create_form } data['html_article_create_form'] = render_to_string( 'article/create_article.html', context, request=request ) return JsonResponse(data) CBV with FormView: class ArticleCreateView(FormView): template_name = 'article/create_article.html' form_class = ArticleForm form_dict = { 'Article_create_form': ArticleForm } def get(self, request): data = dict() context = … -
django daphne ModuleNotFoundError : 'settings'
I made a django project using channels. And I want to deploy it. Because my project uses channels, I should set up ASGI based environment. I pushed my project and succeeded. So I got URL address. https://demo-multichat.herokuapp.com As you can see, Application error occured. I got log. $ heroku logs 2017-09-07T06:03:55.893921+00:00 app[worker.1]: result = connection.blpop(list_names, timeout=self.blpop_timeout) 2017-09-07T06:03:55.893925+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/site-packages/redis/client.py", line 1269, in blpop 2017-09-07T06:03:55.894950+00:00 app[worker.1]: return self.execute_command('BLPOP', *keys) 2017-09-07T06:03:55.894954+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/site-packages/redis/client.py", line 673, in execute_command 2017-09-07T06:03:55.895473+00:00 app[worker.1]: connection.send_command(*args) 2017-09-07T06:03:55.895477+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/site-packages/redis/connection.py", line 610, in send_command 2017-09-07T06:03:55.895972+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/site-packages/redis/connection.py", line 585, in send_packed_command 2017-09-07T06:03:55.895968+00:00 app[worker.1]: self.send_packed_command(self.pack_command(*args)) 2017-09-07T06:03:55.896440+00:00 app[worker.1]: self.connect() 2017-09-07T06:03:55.896444+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/site-packages/redis/connection.py", line 489, in connect 2017-09-07T06:03:55.896869+00:00 app[worker.1]: raise ConnectionError(self._error_message(e)) 2017-09-07T06:03:55.896892+00:00 app[worker.1]: redis.exceptions.ConnectionError: Error 111 connecting to localhost:6379. Connection refused. 2017-09-07T06:03:56.097153+00:00 heroku[worker.1]: Process exited with status 1 2017-09-07T06:04:35.728878+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=demo-multichat.herokuapp.com request_id=ae95450d-249f-46e4-af5e-fd69b3339fbd fwd="165.132.5.143" dyno= connect= service= status=503 bytes= protocol=http 2017-09-07T06:04:36.537336+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=demo-multichat.herokuapp.com request_id=5a48b0e9-0fae-46b2-9885-f1a8390b8eb9 fwd="165.132.5.143" dyno= connect= service= status=503 bytes= protocol=http 2017-09-07T06:04:37.170094+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=demo-multichat.herokuapp.com request_id=db7f5507-c748-4ae5-9718-379cacf3e8e1 fwd="165.132.5.143" dyno= connect= service= status=503 bytes= protocol=http 2017-09-07T06:05:50.020700+00:00 app[api]: Scaled to web@1:Free worker@1:Free by user juhyun1849@gmail.com 2017-09-07T06:05:56.482746+00:00 heroku[web.1]: Starting … -
Django : How to add image path in View
I am trying to convert TIF image format to JPEG using Pillow PIL. But the image should not be in static folder. It should be imported remotely or from given path. I tried this but its not working :- im = Image.open('C:\Users\100368969.TIF') im.save('C:\Users\100368969.jpeg') Development enviornment is Windows. Thanks in advance -
Download files with selenium when get a post with json
Hello I want to know that send a json to django url and get link from it. Than send it via scp. It works when I make as another source file and give a url through argv. But when I put same code into my view.py file, it doesn't work. I don't know what is wrong plz help me @csrf_exempt def download(request): message = ((request.body).decode('utf-8')) return_json_str = json.loads(message) dl_dir = '/home/ubuntu/Downloads' url = return_json_str['link'] display = Display(visible=0, size=(800, 600)) display.start() chrome_options = webdriver.ChromeOptions() prefs = {"download.default_directory": '/home/ubuntu/Downloads'} chrome_options.add_experimental_option("prefs", prefs) driver = webdriver.Chrome(chrome_options=chrome_options) driver.set_window_size(800, 600) driver.get('http://login/') driver.find_element_by_name('mb_id').send_keys('id') driver.find_element_by_name('mb_password').send_keys('passwd') driver.find_element_by_class_name('login-button').click() driver.get(url) time.sleep(1) driver.find_element_by_xpath('//*[@id="mw_basic"]/table[2]/tbody/tr[6]/td/a[1]').click() time.sleep(5) display.popen.kill() driver.quit() os.system('scp /home/ubuntu/Downloads/* user@ip.gq:~/Files') time.sleep(10) os.system('rm /home/ubuntu/Downloads/*') return JsonResponse({ }) -
django.db.utils.IntegrityError: NOT NULL constraint failed: app.area_id
When I run ./manage.py migrate,error happens django.db.utils.IntegrityError: NOT NULL constraint failed: app.area_id . models.py is class Area(models.Model): name = models.CharField(max_length=20, verbose_name='area', null=True) class User(models.Model): name = models.CharField(max_length=200,null=True) age = models.CharField(max_length=200,null=True) area = models.ForeignKey('Area', default="") class Prefecture(models.Model): name = models.CharField(max_length=20, verbose_name='city') area = models.ForeignKey('Area') class City(models.Model): name = models.CharField(max_length=20, verbose_name='region') prefecture = models.ForeignKey('Prefecture') class Price(models.Model): name = models.CharField(max_length=20, verbose_name='price') PRICE_RANGE = ( ('a', 'under500'), ('b', '500-1000'), ('c', 'upper1000'), ) price_range = models.CharField(max_length=1, choices=PRICE_RANGE) city = models.ForeignKey('City') When I wrote area = models.ForeignKey('Area'),I got an error You are trying to add a non-nullable field 'area' to transaction without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py. What is wrong?How can I fix this? -
Django - How to display two texts of equal length line by line?
For example: text_1 = "asd 13 awgg aeg wef 234 adfgg asdtt ..." text_2 = "ASD 13 AWGG AEG WEF 234 ADFGG ASDTT ..." desired_output_1 = Both texts are displayed line by line (one line of text_1 on top of another line of text_2, and such. Not side-by-side) in a div. less_desired_output = "asd ASD 13 13 awgg AWGG aeg AEG wef WEF 234 234 adfgg ADFGG asdtt ASDTT ..." For illustration's sake, I use upper and lower case here, but the actually texts cannot be so easily converted. Both texts are very long and have words separated by spaces. Each text is stored in a field of the same model. How can I achieve this in the final html output? -
Django Template Tag - Display only one value in nested for loop
I'm working on a Django web app and have the following query: I have a model called 'AppQoSList' which lists the applications available to all users. I have then another model called 'BasicAppSDWANProfiles' which has a ManyToMany relationship with 'AppQoSList' . In short, it means a user can have multiple 'BasicAppSDWANProfiles' associated to his account and multiple AppQoS can be within a particular BasicAppSDWANProfiles: class AppQoSList(models.Model): app_qos_name = models.CharField(max_length=50, blank=None, null=True) app_qos_description = models.CharField(max_length=500) def __str__(self): return u'%s' % self.app_qos_name class BasicAppSDWANProfiles(models.Model): profile_name = models.CharField(max_length=30) profile_basic_app_qos = models.ManyToManyField(AppQoSList) tenant_id = models.ForeignKey(Tenant, default=3) I'm facing issue in my template when I try to display the list of apps available and the associated BasicAppSDWANProfile: {% for app in apps %} {% for profile_app in sdwan_prof %} {% for specific_app in profile_app.profile_basic_app_qos.all %} {% ifchanged profile_app.pk %} {% if app.pk == specific_app.pk %} <td><h4><span class="label label-primary">{{ profile_app.profile_name }}</span></h4></td> {% else %} <td><h4><span class="label label-warning">Not Assigned</span></h4></td> {% endif %} {% endifchanged %} {% endfor %} {% endfor %} {% endfor %} Issue with this code is that the 'Not Assigned' row is displayed 3 times on each row (which corresponds to the number of BasicAppSDWANProfiles associated with this user): Would you have any solution … -
How can Allow to users create apps on django
I'm a student from University. I have a huge doubt that has been going around in my head for a long time. I am not new and not old in "Django Framework" and wanted to know if it is possible to somehow do the following with "Django": I have a project which is to allow users to register on my site, take them to the user control panel and there to create a page and / or space on the website, eg: A user registers at the URL: mysite / accounts / register / Go to your control panel: / dashboard / user_1 And then that user is allowed to create a page or space on my website, an example create a "school": / schools / X_NAME_SCHOOL / And in that school can manage things about your school and can enter students, teachers etc ... Then another "User 2" user can also create an account, open a "page" for their school and be able to do the same, but without one school being able to see what the other has. schools / Y_NAME_SCHOOL / It's possible? Is it possible with Django? What things do I need to achieve this? What … -
How to return id after saving a record django rest frwamework
How to return id after saving a record django rest frwamework. I'm trying to get the saved object right after saving. Registration is successful, but the id is not returned. empresa = EmpresaCreateSerializer(data=data) empresa.user = user_id if(empresa.is_valid()): empresa.save() print(empresa.id) else: return Response(empresa.errors) AttributeError: 'EmpresaCreateSerializer' object has no attribute 'id' Model class Empresa(models.Model): nome = models.CharField(max_length=255, null=True) cnpj = models.CharField(max_length=15, null=True) user = models.ForeignKey(User) def __str__(self): return self.nome Serializer class EmpresaCreateSerializer(serializers.ModelSerializer): nome = serializers.CharField(allow_blank=True, allow_null=True) cnpj = serializers.CharField(allow_blank=True, allow_null=True) class Meta: model = Empresa fields = ('id','nome', 'cnpj', 'user')