Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use Django with Python3?
I've been following the official Django tutorial, but I cannot get it to work with Python 3. I used: django-admin startproject mysite in order to create a site, but it runs on Python2... Since I know all the syntax for Python3 I would really like to find a way to code in Python3 Thank you very much ! -
Adding Django MultipleChoiceField one after the other using Javascript
I am working on a Django views based on the following form: class MyForm(forms.Form): def __init__(self, data, examen, *args, **kwargs): super(MyForm, self).__init__(data, *args, **kwargs) self.fields['q1'] = forms.MultipleChoiceField( label=mark_safe("Label question 1"), required=True, widget=forms.CheckboxSelectMultiple, choices=(('1', 'answer 1'), ('2', 'answer 2'), ('3', 'answer 3')) ) self.fields['q2'] = forms.MultipleChoiceField( label=mark_safe("Label question 2"), required=True, widget=forms.CheckboxSelectMultiple, choices=(('1', 'answer 4'), ('2', 'answer 5'), ('3', 'answer 6')) ) ... #TODO : add questions q3 to q9 self.fields['q10'] = forms.MultipleChoiceField( label=mark_safe("Label question 10"), required=True, widget=forms.CheckboxSelectMultiple, choices=(('1', 'answer 28'), ('2', 'answer 29'), ('3', 'answer 30')) ) Il would like to display on a single view self.fields['q1'] with a [submit] button. The idea is for the user to select the answer he considers as correct and the hit the [submit] button. Following that self.fields['q1'] will turn into read-only and self.fields['q2'] will display just below with again a [submit] button... and son on until self.fields['q10']. I do believe that the only way to achieve that is to use Javascript (and even JQuery or any other library). The problem is that I'm not very familiar with Javascript and would gladly appreciate hints on how to tackle that issue. Thank you for what you can do! PS: I'm happy to change my Django design … -
how to set django 2.1 database for production for heroku postgresql?
Why I am asking this question? Ans:My db rows were deleted and came back to original position after creating another user and added some rows to table by him. I came to know that heroku refreshes postgre sql database and added django_heroku. Here are the steps I followed: created an app. hosted on heroku. added heroku_django package in settings as it will cover dj_database_url for django 2.1 python manage.py makemigrations (in local). git push github. git push heroku. heroku run python manage.py migrate. -
Django Allow User to Add a New Item to a List
I have a todo website that would allow users to create a list, and have them create events and specify which list to put it in. Right now, I have a Reminder model that contains a list with a General option: class Reminder(models.Model): remind_types = [('Regular', 'Regular'), ('Long Term', 'Long Term')] remind_lists = [('General','General')] title = models.CharField(max_length=100) description = models.TextField() remind_time = models.DateTimeField(blank=True) parent_user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) type_of_remind = models.CharField(max_length=12, choices=remind_types, default='Regular') remind_list = models.CharField(max_length=20, choices=remind_lists, default='General') complete = models.BooleanField(default=False) I was thinking of creating a form that would have the user input a title, and add the title to remind_list. I would have a menu that allows the user to view reminders based on a specific list, and have reminders passed through like this: from .models import remind_lists @login_required(login_url='/login') def home(request): user = get_object_or_404(User, username=request.user.username) context = { 'events': ToDoItem.objects.filter(parent_user=user), 'reminders': Reminder.objects.filter(parent_user=user, type_of_remind='Regular'), 'long_term_reminders': Reminder.objects.filter(parent_user=user, type_of_remind='Long Term'), } for list_menu_name in remind_lists: context[list_menu_name] = Reminder.objects.filter(parent_user=user, type_of_remind='Long Term', remind_list=list_menu_name) return render(request, 'main/home.html', context) But I'm kind of lost on how to do this. I was thinking of creating a model with just a CharField, but I don't know how to add just the name into the list of remind_lists. … -
SMTPSenderRefused at /password-reset/ Authentication Required
I am adding password reset feature in my Django app, here is the code in settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('EMAIL_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASSWORD') if I replace last two lines with: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'myemail@here.com' # this EMAIL_HOST_PASSWORD = 'passwordOfEmailHere' # this this one works fine, this is the error I get when I use environment variables: Environment: Request Method: POST Request URL: http://localhost:8000/password-reset/ Django Version: 2.2.7 Python Version: 3.7.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blogApp', 'users.apps.UsersConfig', 'crispy_forms'] 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: File "C:\Users\pytuts\Desktop\prac.py\django-proj\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\pytuts\Desktop\prac.py\django-proj\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\pytuts\Desktop\prac.py\django-proj\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\pytuts\Desktop\prac.py\django-proj\lib\site-packages\django\views\generic\base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "C:\Users\pytuts\Desktop\prac.py\django-proj\lib\site-packages\django\utils\decorators.py" in _wrapper 45. return bound_method(*args, **kwargs) File "C:\Users\pytuts\Desktop\prac.py\django-proj\lib\site-packages\django\utils\decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "C:\Users\pytuts\Desktop\prac.py\django-proj\lib\site-packages\django\contrib\auth\views.py" in dispatch 220. return super().dispatch(*args, **kwargs) File "C:\Users\pytuts\Desktop\prac.py\django-proj\lib\site-packages\django\views\generic\base.py" in dispatch 97. return handler(request, *args, **kwargs) File "C:\Users\pytuts\Desktop\prac.py\django-proj\lib\site-packages\django\views\generic\edit.py" in post 142. return self.form_valid(form) File "C:\Users\pytuts\Desktop\prac.py\django-proj\lib\site-packages\django\contrib\auth\views.py" in form_valid 233. form.save(**opts) File "C:\Users\pytuts\Desktop\prac.py\django-proj\lib\site-packages\django\contrib\auth\forms.py" in save … -
Django router withe multiple tables
I settled a django router to link my datatables to the rest api. To do so, I have my models given by: class Lab(models.Model): nom = models.CharField(max_length=50) ville = models.CharField(max_length=50) and its serialization method like this: class LabSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Lab fields = ('url', 'nom', 'ville', 'pk') To access this table, I created a ViewSet in a views file like this : class LabViewSet(viewsets.ModelViewSet): queryset = Lab.objects.all() serializer_class = LabSerializer And in the urls file, I register my view like this : router.register('labs', LabViewSet) This is working, but I'd like to add a new table, Member, linked to the Lab table : class Member(models.Model): email = models.EmailField() nom = models.CharField(max_length=50) prenom = models.CharField(max_length=50) lab = models.ForeignKey(Lab, on_delete=models.CASCADE) How can I access the data throuht a single request joining both tables ? -
How do i update a date field of a user when the admin form is saved?
I have built a django application that is used to store the notes of a meeting. The studio note object is called StudioMeetingNote and it has 2 foreign key fields with the CustomUser model, namely secretary and chairman. Each CustomUser instance has 2 date fields namely last_date_chairman and last_date_secretary. When a user is assigned chairman in the StudioMeetingNote form I want the last_date_chairman field of this user to get the same value as the date assigned to the field meeting_start_date field that belongs to the StudioMeetingNote itself. The same goes for last_date_secretary. I decided to use the def save_model method for this. It resides in the StudioMeetingNoteAdmin class that represents the StudioMeetingNote class in the admin section. The entire implementation looks like this: class StudioMeetingNoteAdmin(admin.ModelAdmin): fields = (('meeting_start_time', 'meeting_end_time'), ('chairman', 'secretary'), 'absent_persons',) # fieldsets = [ # ('Tijden', {'fields': ['meeting_start_time', 'meeting_end_time']}), # ('Wie is de voorzitter/notulist', {'fields': [('chairman', 'secretary')]}), # ('Opkomst', {'fields': [('attending_persons', 'absent_persons')]}), # ] inlines = [OpeningAndParticularitiesInline, ActionListPointInline, RemarksPriorMeetingInline, IssuesToAddressInline, OurNextMoveInline, QuestionRoundInline] list_filter = ['meeting_start_time'] search_fields = ['meeting_start_time'] list_display = ('meeting_start_time', 'chairman', 'secretary') save_as = True def save_model(self, request, obj, form, change): save_user = False if 'chairman' in form.changed_data: obj.chairman = form.cleaned_data['chairman'] obj.chairman.last_date_chairman = form.cleaned_data.get('meeting_start_date') save_user = True … -
Dynamic choices for django forms
I'm building a booking form, and want to allow users to pick a date of booking from available dates in the next 60 days. I get the next 60 days by: base = datetime.date.today() date_list = [base + datetime.timedelta(days=x) for x in range(60)] Then I subtract already booked dates which are stored in the db: bookings = list(Booking.objects.all()) primarykeys = [] unav = [] for b in bookings: primarykeys.append(b.pk) for p in primarykeys: unav.append(Booking.objects.get(pk=p).booking_date) for date in unav: if date in date_list: date_list.remove(date) Then I change the result into tuple for the forms(not sure if this is right?):` date_list = tuple(date_list) Then I pass it into the form field as such: booking_date = forms.ChoiceField(choices=date_list, required=True) This gives me an error of cannot unpack non-iterable datetime.date object And now am I stumped...how can I do this? I have a feeling i'm on the complete wrong path. Thanks in advance -
Reverse for 'news_tag' with no arguments not found. 1 pattern(s) tried: ['news/tags/(?P<tag_name>[^/]+)/$']
my urls . I have to load the tags in new url but i ended up in this error from django.urls import path from news import views urlpatterns =[ path('create/',views.CreateNewsView.as_view(),name='create_news'), path('<str:category>/',views.NewsCategoryView.as_view(),name='category_news'), path('<str:category>/<int:pk>/<str:slug>/',views.NewsDetailView.as_view(),name='detail_news'), path('tags/<str:tag_name>/',views.view_tag ,name='news_tag'), path('<str:category>/<int:pk>/<str:slug>/comment/',views.create_comment,name='create_comment'), path('<str:category>/<int:pk>/<str:slug>/delete/',views.NewsDeleteView.as_view(),name='delete_news'), path('<str:category>/<int:pk>/<str:slug>/update/',views.NewsUpdateView.as_view(),name='update_news'), ] my views: this view is to load to my news from the tags def view_tag(request,tag_name): tag= Tag.objects.get(pk=tag_name) news= tag.page_set.all() return render(request,'news/tags.html',{"tag_name":tag_name,'news':news}) my models:I have created this models without Taggable Manager() to create tags class Tag(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class News(models.Model): CATEGORY=(("0","Politics"),("1","Sports"),("2","Health"),("3","Business"),("4","International"),("5","Finance")) title=models.CharField(max_length=250) story= models.TextField() count= models.IntegerField(default=0) tags = models.ManyToManyField(Tag) video_url = models.URLField(max_length=270, null=True) #makemigrations garna baki xa category= models.CharField(choices=CATEGORY, max_length=2) slug=models.SlugField(max_length=270,blank=True,null=True) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) cover_image=models.ImageField(upload_to="uploads") author= models.ForeignKey(User, on_delete=models.SET_NULL,null=True) video_image = models.ImageField(null=True) -
How to run on heroku wss?
Everything works on the local server, but no messages are sent to Heroku. I run heroku run bash and python manage.py run_chat_server Server starts without errors. My settings.py CHAT_WS_SERVER_HOST = '0.0.0.0' CHAT_WS_SERVER_PORT = 5002 CHAT_WS_SERVER_PROTOCOL = 'wss' I am using https protocol. In the browser console WebSocket 'connection to wss://0.0.0.0:5002/dfs5k7c05k20w236xxhvelsrfm2adpgo/username' failed: Error in connection establishment: net::ERR_SSL_PROTOCOL_ERROR It may be necessary to start the server with cert.pem? How to do it on heroku? It seems he creates them himself... -
Getting error : Got AttributeError when attempting to get a value for field `profile` on serializer `UserSerializer`
i am new here in django python so pardon me for my silly mistakes, When i try to run api /api/v1/users/ getting error : Got AttributeError when attempting to get a value for fieldprofileon serializer UserSerializer. , here i have placed my whole code, i know i did some little mistake, but i didn't find it yet, can anyone please look my code and help me to resolve this issue ? any help will be really appreciated, thanks in advance serializers.py from rest_framework import serializers from .models import Songs from .models import UserProfile from django.contrib.auth.models import User class SongsSerializer(serializers.ModelSerializer): class Meta: model = Songs fields = ("title", "artist") class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('title', 'dob', 'address', 'country', 'city', 'zip', 'photo') class UserSerializer(serializers.HyperlinkedModelSerializer): profile = UserProfileSerializer(required=True) class Meta: model = User fields = ('url', 'email', 'first_name', 'last_name', 'password', 'profile') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): profile_data = validated_data.pop('profile') password = validated_data.pop('password') user = User(**validated_data) user.set_password(password) user.save() UserProfile.objects.create(user=user, **profile_data) return user def update(self, instance, validated_data): profile_data = validated_data.pop('profile') profile = instance.profile instance.email = validated_data.get('email', instance.email) instance.save() profile.title = profile_data.get('title', profile.title) profile.dob = profile_data.get('dob', profile.dob) profile.address = profile_data.get('address', profile.address) profile.country = profile_data.get('country', profile.country) profile.city = profile_data.get('city', profile.city) … -
How to display object names on a Django Template?
Just Started learning Dango and i got some problems on understanding how to display the name of a object and not it's ID, here I have two tables, one of books and other of i'ts category and in the books table i have a ForeignKey pointing to the category. You can see my codes: My models.py #class for making the book table on the db class Books(models.Model): ... category_cod_category = models.ForeignKey( 'Editora', on_delete = models.CASCADE ) ... class Meta: db_table = 'Books' # class for the category tables class Category(models.Model): name_category = models.CharField( max_length = 45 ) class Meta: db_table = 'category' My forms.py class BooksForm(forms.ModelForm): class Meta: model = Books fields = [ ... ,'category_cod_category',] The view.py that i'm struggling to understand def book(request): if request.method == 'POST': form = BooksForm(request.POST or None) print(form.errors) if form.is_valid(): try: form.save() return redirect('/show') except: pass else: print("form not valid") else: form = BooksForm() return render(request, 'index.html', {'form':form}) And the Template index.html that should show the category name but it only returns the ID <form method="POST" class="post-form" action="/livro"> {% csrf_token %} <!-- not pasting working forms --> <div class="form-group row"> <label class="col-sm-2 col-form-label">Books's Category:</label> <div class="col-sm-4"> {{ form.category_cod_category }} </div> </div> <div class="form-group … -
is there any difference between while using url and path in django web development
is there any difference between while using url and path in django web development from django.conf.urls import url url(r'^about/', views.home, name='blog.about') and from djano.urls import path path('about/', views.home, name='blog.about') ? -
Is it possitble to execute a python(django) function immediately on vs code?
I want to execute a python function in vs code directly when I set a breakpoint when debugging. Just like Immediate window on Visual Studio -
Django REST Framework Multiple OR'd Custom Permissions' Message Not Shown
I'm trying to write a RetrieveUpdateDestroyAPIView where the permission classes are set as follows: permission_classes = (IsUserCat | CanDogsRetrieveObject,) permissions.py: class IsUserCat(IsAuthenticated): def has_object_permission(self, request, view, obj): return super().has_object_permission(request, view, obj) and request.user.species == SPECIES_CAT def has_permission(self, request, view): return super().has_permission(request, view) and request.user.species == SPECIES_CAT class IsUserDog(IsAuthenticated): def has_object_permission(self, request, view, obj): return super().has_object_permission(request, view, obj) and request.user.species == SPECIES_DOG def has_permission(self, request, view): return super().has_permission(request, view) and request.user.species == SPECIES_DOG class CanDogsRetrieveObject(IsUserDog): message = "Some custom message." def has_permission(self, request, view): return super().has_permission(request, view) def has_object_permission(self, request, view, obj): return super().has_object_permission(request, view, obj) and obj.expiry_date >= timezone.now().date() So basically, the first permission class checks if the user is a cat, if so, the user can retrieve the object; if not, the second permission class checks if the user is a dog and if the object in question is expired. If it's expired, a custom error message must be displayed, but it doesn't. If I don't OR them, and instead just use CanDogsRetrieveObject then the issue gets resolved. Why is this the case? -
How to filter and count query set in django template?
I have this model: class Application(Model): is_paid = BooleanField(default=False) and this view: def my_view(request): template_name = 'my_template.html' context = {} applications = Application.objects.all() context.update({'applications': applications,}) return render(request, template_name, context) and have this template: <body> All: {{ applications.count }} <!-- Paid: I want to show the count of paid applications in here. --> <!-- UnPaid: I want to show the count of unpaid applications in here. --> </body> What I want to do is that filter the applications based on the is_paid field and count them. I do not want to do it in the view. I want to do it in the template to avoid making view complicated and big. How should I do it? -
Override e-mail header in form django-crispy-forms for django-allauth
I can not find a way to redefine the header and placeholder for the mail field in the form of a django-allauth created using django-crispy-forms. -
Model with manyToMany InvalidCursorName in admin
I have a problem with Django and Postres. Python 3.5 Django 2.2.7 psycopg2 2.8.4 postgres 9.5.19 Models: class Model1(models.Model): model1_name = models.CharField(max_length=20) class Model2(models.Model): model2_name = models.CharField(max_length=20) model_keys = models.ManyToManyField(Model1, blank=True) Postgress DB is empty: my_base=> \d No relations found. I do migrations... python3 manage.py makemigrations project/migrations/0004_model1_model2.py - Create model Model1 - Create model Model2 python3 manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, engine_st, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying myproject.0001_initial... OK Applying myproject.0002_auto_20191129_1339... OK Applying myproject0003_auto_20191129_1340... OK Applying myproject.0004_model1_model2... OK Applying sessions.0001_initial... OK ... , but the admin panel has error (Page for create new object): Exception Type: InvalidCursorName Exception Value: cursor "_django_curs_140479737550592_1" does not exist Does anyone know a solution to this problem? There is no such problem on SQLite. -
My Django app is running after I deployed it
The link is Mejoshjones.com it was the passenger app will show what’s wrong with the app. I don’t know where to start for as debugging This is what I think is wrong from tinymce import HTMLField ImportError: cannot import name 'HTMLField' from 'tinymce' (/home/powevtec/virtualenv/mejoshjones.com/test/3.7/lib/python3.7/site-packages/tinymce/init.py) -
Language for allowing users to write simple mathematical functions with no state change?
I am writing a small simulation where users can trade assets and I want them to be able to trade options too. Options are basically mathematical functions f(Asset_price : [float]) -> float that should not need to make any state change. It would be optimal if the users could supply these functions themselves. The app is written in python/django but of course I cannot just let them upload python code and execute that. Is there some simple way to still let the users handcode these functions? My idea would be some very simplistic language that I can easily call from python that only allows the users to do some basic mathematical operations in the function f and not allowing any state change to the environment. Is there something like that out there? I am also open for different suggestions on how to achieve my goal. -
Django2.2.7 + Mysqlclient installation error + Ubuntu 16.04
I have successfully installed python3.6.* and Django2.2.*, MySQL-server However in the virtualenv I am getting error while installing the MySQL client. x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -Dversion_info=(1,4,4,'final',0) -D__version__=1.4.4 -I/usr/include/mysql -I/usr/include/python3.6m -I/var/www/venv/include/python3.6m -c MySQLdb/_mysql.c -o build/temp.linux-x86_64-3.6/MySQLdb/_mysql.o x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-Bsymbolic-functions -Wl,-z,relro -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 build/temp.linux-x86_64-3.6/MySQLdb/_mysql.o -lmysqlclient -lpthread -lz -lm -lrt -lssl -lcrypto -ldl -o build/lib.linux-x86_64-3.6/MySQLdb/_mysql.cpython-36m-x86_64-linux-gnu.so /usr/bin/ld: cannot find -lssl /usr/bin/ld: cannot find -lcrypto collect2: error: ld returned 1 exit status error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ---------------------------------------- ERROR: Command errored out with exit status 1: /var/www/venv/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-fezj4ikj/mysqlclient/setup.py'"'"'; __file__='"'"'/tmp/pip-install-fezj4ikj/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-kodyrb_q/install-record.txt --single-version-externally-managed --compile --install-headers /var/www/venv/include/site/python3.6/mysqlclient Check the logs for full command output. Does anyone have help guide to resolve this problem? -
Importing json files in models with field definition using Django admin
I am trying to import json data files by parsing into Django data models. I have defined a table with the "Entidad" where the json file is uploaded with the data. Through the actions of Django in admin I intend to upload the file, for example "Articles", launch the action, load the json and parse or match each field by importing the data into the models. class Entidad(TimeStampedModel): nombre = models.CharField(max_length=100) archivo = models.FileField(upload_to="importaciones/entidades/", help_text="Fichero formato *.json") Another "Relacion" table where the "origen" field (in the json) "destino" field of the model is indicated: class Relacion(TimeStampedModel): entidad = models.ForeignKey("importaciones.Entidad", related_name="relaciones", on_delete=models.CASCADE) origen = models.CharField(max_length=50, help_text="Nombre del campo de la columna del fichero.") destino = models.CharField(max_length=50, help_text="Nombre del campo de la base de datos.") modelo = models.CharField(max_length=50, help_text="Nombre tabla de datos.") The admin TabularInline: class RelacionInline(admin.TabularInline): model = Relacion class EntidadAdmin(admin.ModelAdmin): inlines = [ RelacionInline, ] actions = ['importar_datos',] def importar_datos(self, request, queryset): for entidad in queryset: with open(entidad.archivo.path) as f: data = json.load(f) importa(data, entidad.relaciones) self.message_user(request, "Se ha importado xxx") importar_datos.short_description = "Importar datos seleccionado(s)" admin.site.register(Entidad, EntidadAdmin) Example of the json file. It should be noted that there are related tables: { "root": { "Products": [ { "supplierCode": "34523", "date": … -
AttributeError: 'QuerySet' object has no attribute 'tags'
My views . this view contains error in news.tags class NewsDetailView(DetailView): model = News template_name='news/detail_news.html' context_object_name= 'news' def get_context_data(self, **kwargs): news=News.objects.all() tags=news.tags.all() context = super().get_context_data(**kwargs) context['comments'] = Comment.objects.filter(news=self.object) context['my_likes'] = Like.objects.filter(news=self.object) context['popular_news'] = news.order_by("-count")[:6] context['tags'] = tags # context["tags"] = TaggableManager().bulk_related_objects(self.object) self.object.count = self.object.count + 1 self.object.save() return context this is my models . i have created this to make a news . and i want to add tags in my news without TaggableManager() class Tag(models.Model): name = models.CharField(max_length=30) class News(models.Model): CATEGORY=(("0","Politics"),("1","Sports"),("2","Health"),("3","Business"),("4","International"),("5","Finance")) title=models.CharField(max_length=250) story= models.TextField() count= models.IntegerField(default=0) tags = models.ManyToManyField(Tag) video_url = models.URLField(max_length=270, null=True) #makemigrations garna baki xa category= models.CharField(choices=CATEGORY, max_length=2) slug=models.SlugField(max_length=270,blank=True,null=True) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) cover_image=models.ImageField(upload_to="uploads") author= models.ForeignKey(User, on_delete=models.SET_NULL,null=True) video_image = models.ImageField(null=True) def get_absolute_url(self): return reverse("detail_news",kwargs={"category":self.get_category_display(), "pk":self.pk, "slug":self.slug}) -
Doesn't appear the selected option in <select>
I'm trying to create dynamically some check-boxes in my django project, what I'm doing is: <form action="#" method="post" target="#"> {% for node in Last_val_nodes %} <input type="checkbox" name="{{node.0}}" value="#" class="nodos_check_ruta"> {{node.0}}<br> {% endfor %} </form> Where Last_val_nodes is a list of lists that comes from my views.py and I'm interested in the first value of this "sublists". Up to this point all is good, but now what I want to do is know what checkbox is selected. That's why I'm writing in name {{node.0}}, because my js do the next, if( $('.nodos_check_ruta').is(':checked') ) { var name = $(this).attr("name"); alert(name); } But the alert is undefined. Who can I know the selected check-boxes? If there more than one selected, how can I know it? I want to save all the selected in a list. Thank you. -
Django template tag doesn't see scope variable
I am trying to dynamically include Django template based on AngularJS scope variable. Variable contains "image", "audio" or "video" values in string format. And I am using 'with' tag and 'add' filter to get template path and name e.g. "record/audio.html": {% with template_name=record.filetype|add:".html" %} {% include "record/"|add:template_name %} {% endwith %} Unfortunately, I end up with error message: "TemplateDoesNotExist /record/.html". It looks like the variable doesn't exist even though when I try to print it with [[ record.filetype ]] it works just fine. I am guessing the scope is not loaded yet when the 'with/include' tags are executed. I load the scope with 'ng-init' in 'main' html tag which I am not sure is the best practice but I don't know how else I should do it. <main ng-controller="ProjectCtrl" ng-init="getRecord('{{ project }}')" ng-cloak> {% with template_name=record.filetype|add:".html" %} {% include "record/"|add:template_name %} {% endwith %} <!-- some other code -->