Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why we are checking if the request is Post in django Views.py?
I'm a beginner in Django so while learning I found something. some people are doing a request check for example def register(request): if request.method =='POST': # Register user redirect() else: return render(request,'accounts/register.html') so I found it so unnecessary because in my HTML form the action and method are already specified it <form action="{% url 'register' %}" method="POST"> so it makes no sense, as we only making a post request to register and it won't get to it by any other way . so am I wrong ? and thank you everyone for your time -
Combine queries from 2 inherited Django models
I would like to perform a prefetch. The point is: I have a baseModel and inherited models that are liked to other models. But my baseModel isn't linked with them. Here is the speudo code: class Author(models.Model): name = models.CharField() class Movie(PolymorphicModel): title = models.CharField() author = models.ForeignKey('Author') class EnglishMovie(Movie): pass class FrenchMovie(Movie): pass class Subtitle(models.Model): movie = models.ForeignKey('FrenchMovie', related_name='subtitle') text = models.CharField() As you can see, FrenchMovie is linked to subtitles, but EnglishMovie isn't. I would like to prefetch all my movie, and prefetch the subtitles as well. I've tried several methods: def get_queryset(self): return Movie.objects.prefetch_related('author', 'subtitle').all() I get: ValueError: Cannot query "EnglishMovie object (1)": Must be "FrenchMovie" instance. def get_queryset(self): q1 = Movie.objects.prefetch_related('author').all() q2 = FrenchMovie.objects.prefetch_related('subtitle').all() return q1 | q2 I get: AssertionError: Cannot combine queries on two different base models. Any tips ? Thanks a lot. -
why Django Admin Panel can not add any record to a table?
I hava a django admin panel , when i want to add some records in a table using django admin panel i get this error : IntegrityError at /admin/pool/partoorders/add/ (1452, 'Cannot add or update a child row: a foreign key constraint fails (`projectname`.`orders`, CONSTRAINT `orders_ibfk_3` FOREIGN KEY (`user_phone`) REFERENCES `users` (`phone`) ON DELETE NO ACTION ON UPDATE NO ACTION)') -
how to make user friendly voting system in django
This Code is working perfectly. The only thing I want to change is submit button "Vote" into "Voted" after user voted the option ,instead of displaying error message " You Already Voted".So that the user can know which options he voted already when he logs in to vote the option next time urls.py path('<slug>/',views.options,name='options'), path('<slug>/vote/', views.vote, name='vote'), models.py class Category(models.Model): name = models.CharField(max_length=250) slug = AutoSlugField(populate_from='name') details = models.TextField(blank=True) image = models.ImageField(blank=True,upload_to='categories') views = models.IntegerField(default=0) created = models.DateTimeField(auto_now=True) modified = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) def __str__(self): return self.name class Meta: verbose_name_plural = "Categories" class Option(models.Model): name = models.CharField(max_length=250) slug = AutoSlugField(populate_from='name') image = models.ImageField(blank=True,upload_to='options') details = models.TextField() category = models.ForeignKey(Category, on_delete=CASCADE) votes = models.IntegerField(default=0) active = models.BooleanField(default=True) def __str__(self): return self.name class Vote(models.Model): option = models.ForeignKey(Option, on_delete=CASCADE) voter = models.ForeignKey(User, on_delete=CASCADE) slug = AutoSlugField(populate_from='option') def __str__(self): return self.voter views.py def vote(request,slug): if request.user.is_authenticated: option = Option.objects.get(slug=slug) category = option.category if Vote.objects.filter(slug=slug,voter_id=request.user.id).exists(): messages.error(request,'You Already Voted!') return redirect('rank:options', category.slug) else: option.votes += 1 option.save() voter = Vote(voter=request.user,option=option) voter.save() messages.success(request,'Voted.{} peoples also agree with you.'.format(option.votes-1)) return redirect('rank:options',category.slug) else: messages.error(request,"You have to login first to vote.") return redirect('rank:login') options.html <ol type="1"> <center>{% bootstrap_messages %}</center> {% for option in options %} <div class="col-lg-6 col-md-6 mb-6"> … -
Big file upload gives django.db.utils.OperationalError: (2013, 'Lost connection to MySQL server during query')
I have a view for upload file in my django app. Just at the beginning of the view a do a small db request def upload(request: HttpRequest, model_uid): user = request.user code = Something.objects.get(model_uid=model_uid) ... # do something with the request.FILES['file'] Sometimes, when a user upload a big file, i get a stack trace on: Something.objects.get(model_uid=model_uid) Stack trace Exception: django.db.utils.OperationalError: (2013, 'Lost connection to MySQL server during query') I know there are a lot of questions related to this exception but they are related to big sql queries / operation, not to a small query after a long request due to a large file upload. -
PyCharm Debugger didn't stop at breakepoints in templatetags
PyCharm stopped debugging migrations. Previously It worked pretty well: the debugger stopped at the breakepoint in render function, but today It's not working at all. -
UserAccount matching query does not exist
When I open article i have this error UserAccount matching query does not exist views.py class ArticleDetailView(DetailView, CategoryAndArticleListMixin): model = Article template_name = 'post_detail.html' def get_context_data(self, *args, **kwargs): context = super(ArticleDetailView, self).get_context_data(*args, **kwargs) context['article'] = self.get_object() context['article_comments'] = self.get_object().comments.all() context['form'] = CommentForm context['current_user'] = UserAccount.objects.get(user=self.request.user) return context models.py class UserAccount(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField() favorite_articles = models.ManyToManyField(Article) def __str__(self): return self.user.username def get_absolute_url(self): return reverse('account_user', kwargs={'user': self.user.username}) urls.py urlpatterns = [ url(r'^$', CategoryListView.as_view(), name='base_view'), url(r'category/(?P<slug>[-\w]+)/$', CategoryDetailView.as_view(), name='category-detail'), url(r'account_user/(?P<user>[-\w]+)/$', UserAccountView.as_view(), name='account_user'), url(r'(?P<category>[-\w]+)/(?P<slug>[-\w]+)/$', ArticleDetailView.as_view(), name='article-detail'), url(r'show_article_image/$', DynamicArticleImageView.as_view(), name='article_image'), url(r'add_comment/$', CreateCommentView.as_view(), name='add_comment'), url(r'display_articles_by_category$', DisplayArticlesByCategoryView.as_view(), name='articles_by_category'), url(r'user_reaction$', UserReactionView.as_view(), name='user_reaction'), url(r'registration/$', RegistrationView.as_view(), name='registration'), url(r'login/$', LoginView.as_view(), name='login'),] and html code where using my logic post_detail.html <p class="add_to_favorites {{ article.slug }}"> {% if article in current_user.favorite_articles.all %} <button class="btn btn-disabled">Добавлено в избранное</button> {% else %} <a href=""><button class="btn btn-danger">Добавить в избранное</button></a> {% endif %} -
How can I add custom field to queryset and sorted
I have Product model and my products don’t have available_quantity and prices field because these field are in another service. So I added custom field to my queryset. This is my code; for product in queryset: product.info_bundle = { 'available_quantity': stock_info.get(product.stock_code), 'prices': 100, } I added my custom info_bundle field to queryset. Problem is; I can’t order with queryset.order_by(‘avaliable_quantity’) because I added this. It’s not coming from database therefore SQL cant find the field. -
Django get child object through parent
I was trying to access the child object, through the parent object, as I want to perform different operations depending on the type of the object. What I have is: #models.py class A(models.Model): ... class B(A): field1 = models.CharField(...) ... class C(A): field2 = models.IntegerField(...) I could perform 2 for loops and accomplish what I want: for obj in B.objects.all(): if field1 == 'something': do some operation for obj in C.objects.all(): if field2 == 5: do some other operation But I was thinking, is it not possible to do this with 1 for loop and access the child through the parent? for obj in A.objects.all(): if obj.b and obj.b.field1 == 'something': do some operation elif obj.c and obj.c.field2 == 5: do some other operation I also thought that select_related may do the trick, but it says it works only for ForeignKey. Moreover, I was hoping to get this done, without using additional apps such as django-model-utils or django-polymorphic, because I feel like there should be a simple query operation to do this. -
Django: AuthForbidden at /auth/complete/google-oauth2/: Your credentials aren't allowed
I'm having the same problem as here (but there's no news for the author of the question so it seems it can't be solved). Where could the problem come from? I just want to know if it's a problem of my Django configuration, or a problem on my Google account configuration (this will help me to solve the problem much faster). I try to login with google auth2 only. I've made all the necessary configuration, and here's the whole dump: ERROR:django.request:Internal Server Error: /auth/complete/google-oauth2/ Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.7/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/social_django/utils.py", line 49, in wrapper return func(request, backend, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/social_django/views.py", line 33, in complete *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/social_core/actions.py", line 43, in do_complete user = backend.complete(user=user, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/social_core/backends/base.py", line 40, in complete return self.auth_complete(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/social_core/utils.py", line 259, in wrapper return func(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/social_core/backends/oauth.py", line 405, in auth_complete *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/social_core/utils.py", line 259, in … -
Django Rest-Framework price range additional filter?
I have the following Django view in my Django Rest-Framework API from django_filters.rest_framework import DjangoFilterBackend, RangeFilter, FilterSet from rest_framework.filters import OrderingFilter, SearchFilter from rest_framework import generics from api.serializers import UserSerializer from django.contrib.auth.models import User from rest_framework import permissions from api.permissions import IsOwnerOrReadOnly from MyGameDBWebsite.models import Game, GameDeveloper, GameGenre, GameConsole from api.serializers import GameSerializer, DeveloperSerializer, GenreSerializer, ConsoleSerializer class GameList(generics.ListCreateAPIView): permission_classes = (permissions.IsAuthenticatedOrReadOnly,) serializer_class = GameSerializer filter_backends = (DjangoFilterBackend, OrderingFilter, SearchFilter,) filter_fields = ('owner__username', 'id', 'game_title', 'game_developer_name', 'game_console', 'game_genre', 'game_release_year', 'game_price',) ordering_fields = ('owner__username', 'id', 'game_title', 'game_developer_name', 'game_console', 'game_genre', 'game_release_year', 'game_price',) search_fields = ('game_title', 'game_release_year', 'game_price',) queryset = Game.objects.all() def perform_create(self, serializer): serializer.save(owner=self.request.user) My output URL is the following: http://127.0.0.1:8000/api/?owner__username=&id=&game_title=&game_developer_name=&game_console=&game_genre=&game_release_year=&game_price= I want create a price range so that i can call the API from URL to get the results in a price range -
get field label, help_text and value as context after form submission
I want to send email to the user based on his/her response. How do I set the context so that I can access label, help_text and value of each field in my template. forms.py class ResponseForm(ModelForm): def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) super(ResponseForm, self).__init__(*args, **kwargs) if user: for key, value in question_answer_dict.items(): self.fields[key].help_text = getattr(user, key + '-H') class Meta: model = ResponseModel exclude = ('author', 'submit_count') views.py @login_required def ResponseFormView(request): def mail(): subject = 'Thank you!' email_from = settings.EMAIL_HOST_USER recipient_list = [request.user.email, ] html_message = render_to_string( 'mail_template.html', {'context': suitable_context}) plain_message = strip_tags(html_message) send_mail(subject, plain_message, email_from, recipient_list, html_message=html_message) if request.method == "POST": form = ResponseForm(request.POST) if form.is_valid(): submission = form.save(commit=False) submission.author = request.user submission.save() mail() return render(request, 'thanks.html', {}) else: form = ResponseForm(user=request.user) return render(request, 'response_tem.html', {'form': form}) NB: Each user may have different question and different help_texts. -
Which is best Front End Framework with Django? without loosing django template tags usage
I went through some articles about using django with front end frameworks they are saying, using front end with django is hard thing its like developing three(back end,front end and REST API) projects instead of one. and hard to do CSRF tocken correctly, and may be loose some django built in conventions like form rendering, template tags etc and finally logic might be implemented in twice(back end and front end) Can any one describe which tool is best and easy to use with django without loosing template tags and django other features -
How class-based views determine which template file will be called?
here's the code: # urls.py urlpatterns = [ path("books/", views.BookListView.as_view(), name="books"), ] and the views # views.py class BookListView(generic.ListView): model = Book Book is a class in models.py, this view will using book_list.html template. My question is: Why does it knows what templates will be called? I didnt even give the template_name to it. just like this template_name = 'book_list.html' -
how to use HttpResponseRedirect Reverse in django 2
In Project urls.py path('rank/',include('rank.urls')), In app urls.py path('<slug>/',views.options,name='options'), path('<slug>/vote/', views.vote, name='vote'), In views.py` def options(request,slug):-->this slug belongs to anthoer model #codes def vote(request,slug): -->this slug belongs to anthoer model #codes return HttpResponseRedirect(reverse('TheRanker.rank.views.options') ` -
what should a Django freelancer do at initial step
Currently I am learning Django ,and I also try to enrich my knowledge on python 3.I have a little bit knowledge of Html,CSS,bootstrap If i want to start freelancing what should I do? -
Nginx permissions
I deployed the server with Ubuntu 18, Django, Gunicorn, Nginx And I ran into this problem: everything works great but, When I upload large pictures files in Django, Nginx gives 403 Error Forbidden. I updated the permissions to the folder with static files on 755. It works! But when I upload other files, the rights do not work. I added the user root and user www-data to the folder owner’s group, but nothing has changed. I understand that Nginx has no permissions, but how can I implement the inheritance permissions of new files from the parent folder or will you suggest another solution? -
Reverse for '<WSGIRequest: POST '/signup/'> error on Signup page
I am trying to create a user account and all is well when I use the signup view and form to sign up on the signup html page below is some info but I get this error NoReverseMatch at /signup/ Reverse for '' not found. '' is not a valid view function or pattern name. Request Method: POST Request URL: http://127.0.0.1:8000/signup/ Django Version: 2.1.7 Exception Type: NoReverseMatch Exception Value: Reverse for '' not found. '' is not a valid view function or pattern name. Exception Location: C:\WINDOWS\system32\dev\pastebinclonedirectory\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 622 Python Executable: C:\WINDOWS\system32\dev\pastebinclonedirectory\Scripts\python.exe Python Version: 3.6.8 Python Path: ['C:\WINDOWS\system32\dev\pastebinclonedirectory\pastebin', 'C:\WINDOWS\system32\dev\pastebinclonedirectory\Scripts\python36.zip', 'C:\WINDOWS\system32\dev\pastebinclonedirectory\DLLs', 'C:\WINDOWS\system32\dev\pastebinclonedirectory\lib', 'C:\WINDOWS\system32\dev\pastebinclonedirectory\Scripts', 'c:\users\aadeo\appdata\local\programs\python\python36\Lib', 'c:\users\aadeo\appdata\local\programs\python\python36\DLLs', 'C:\WINDOWS\system32\dev\pastebinclonedirectory', 'C:\WINDOWS\system32\dev\pastebinclonedirectory\lib\site-packages'] Server time: Wed, 13 Mar 2019 06:46:57 +0000 View.py def signup(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect(request,'app/index.html') else: form = UserRegisterForm() return render(request, 'app/signup.html', {'form': form}) forms.py from django import forms from .models import Post from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class Userpostform(forms.ModelForm): class Meta: model = Post fields = ('title','content','private',) class Visitorpostform(forms.ModelForm): class Meta: model = Post fields = ('title','content') URLS.PY in apps folder path('',views.home,name='home'), path('accounts/', include('django.contrib.auth.urls'),name='login'), path('signup/',views.signup,name='signup'), path('accounts/profile/',views.profile,name='profile'), path('logout',views.logout_view,name='logout'), path('userpostnew', … -
Exception Value: strptime() argument 1 must be str, not None
I am trying to get a user input(DateField) from my django app this code gives me the above error Error Code: def home(request): today = datetime.date.today() # If this is a POST request then process the Form data if request.method == 'GET': form = DeadlineForm(request.GET) # instance = form.save() currentdate = datetime.date.today() print(currentdate) userinput = formd.data birthday = datetime.datetime.strptime(userinput, '%m/%d/%Y').date() # print(birthday) days = birthday - currentdate daysLeft = 'Days to your birthday is ' ,+ days return HttpResponse(daysLeft) context = { 'form': form, 'today':today } return render(request, 'calculator/home.html', context) But when I use string date format everything works fine but I want users to be able to insert their own date. code with no error: def home(request): today = datetime.date.today() # If this is a POST request then process the Form data if request.method == 'GET': form = DeadlineForm(request.GET) # instance = form.save() currentdate = datetime.date.today() print(currentdate) # userinput = formd.data birthday = datetime.datetime.strptime('03/15/2019', '%m/%d/%Y').date() # print(birthday) days = birthday - currentdate daysLeft = 'Days to your birthday is ' ,+ days return HttpResponse(daysLeft) context = { 'form': form, 'today':today } return render(request, 'calculator/home.html', context) Please can someone show me how to get a string input from user. -
Django admin onclick function
I created the following features on the Django admin list! admin.py class LawyerAdmin(admin.ModelAdmin): list_display = ('lawyer_idx', 'show_firm_url', 'lawyer_name', 'lawyer_birthday', 'lawyer_mobile', 'lawyer_license_num', 'like_cnt', 'recommend_name', 'register_date', 'status', 'lawyer_agent',) list_filter = ['lawyer_status'] def status(self, obj): if obj.lawyer_status == "W": html = "Awaiting certification<br> <input type='button' value='certification' onclick='lawyer_confirm({0})'>" return format_html(html, obj.lawyer_idx) admin.site.register(Lawyer, LawyerAdmin) When I click the On-Click button, I want to run the following script, but I don't know how. Please help me. 1. I want to implement the on-click function. 2. How to run a script <script> function lawyer_confirm(lawyer_idx) { if (confirm('Certified?') == true) { $.ajax({ url: '/admin/lawyer/view/lawyer_confirm', data: { lawyer_idx : lawyer_idx }, dataType: "json", type: 'post', success: function(result){ alert(result.msg); if (result.code == '0' ) { location.href = result.retURL; } } }); } } </script> -
Add python libraries in Pyinstaller
I am building an executable file using pyinstaller for a django project. I am able to make the executable file using pyinstaller using below command: pyinstaller --onefile --add-binary='/System/Library/Frameworks/Tk.framework/Tk':'tk' --add-binary='/System/Library/Frameworks/Tcl.framework/Tcl':'tcl' --name=topic manage.py But when i run the executable i am getting error importing my python libraries like: Exception Type: AttributeError Exception Value: module 'pandas' has no attribute 'compat' Exception Location: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/PyInstaller/loader/pyimod03_importers.py in exec_module, line 631 How do i add my python libraries in executable file to resolve this error. My Spec file: block_cipher = None a = Analysis(['manage.py'], pathex=['/Users/Python_binaries/topic'], binaries=[('/System/Library/Frameworks/Tk.framework/Tk', 'tk'), ('/System/Library/Frameworks/Tcl.framework/Tcl', 'tcl')], datas=[], hiddenimports=[], hookspath=[], runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher) def get_pandas_path(): import pandas pandas_path = pandas.__path__[0] return pandas_path dict_tree = Tree(get_pandas_path(), prefix='pandas', excludes=["*.pyc"]) a.datas += dict_tree a.binaries = filter(lambda x: 'pandas' not in x[0], a.binaries) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE(pyz, a.scripts, a.binaries, a.zipfiles, a.datas, name='topic', debug=False, strip=False, upx=True, runtime_tmpdir=None, console=True ) -
Django ORM LEFT JOIN on fields with same values
I am writing web-interface for hydrologists. Hydrologist should see table with different hydrological measurements like this. +--------------------+-----------------------------+--------+--------------------------+---------------+ | observation_id | observation_datetime | level | water_temperature |precipitation| +--------------------+-----------------------------+--------+--------------------------+---------------+ | 1 | 2019-03-11 11:00:00 | 11 | 21 | 31 | | 2 | 2019-03-12 12:00:00 | 12 | 22 | 32 | | 3 | 2019-03-13 13:00:00 | 13 | 23 | 33 | | 4 | 2019-03-14 14:00:00 | 14 | 24 | 34 | I have these models for describing measurements class AbstractMeasurement(model.Model): observation_datetime = models.DateTimeField() observation = models.ForeignKey(Observation, on_delete = models.DO_NOTHING) class Meta: abstract = True class Level(AbstractMeasurement): level = models.DecimalField() class AirTemperature(AbstractMeasurement): air_temperature = models.DecimalField() class Precipitation(AbstractMeasurement): precipitation = models.DecimalField() etc. Level the main measurement and measurement cannot be done without level. Level is the basic model. In mysql I can do it by this query SELECT level.observation_id, level.observation_datetime, level.level, water_temperature.water_temperature, precipitation.precipitation, precipitation.precipitation_type from level LEFT JOIN precipitation ON level.observation_datetime = precipitation.observation_datetime AND level.observation_id = precipitation.observation_id LEFT JOIN water_temperature ON level.observation_datetime = water_temperature.observation_datetime AND level.observation_id = water_temperature.observation_id; How I can LEFT JOIN in django with models without foreign key relationship? -
how to get the selected value from dropdown in django
My question is ,i want to get the prefix value(selected) and append into Contract class in the field 'code'. for eg:- prefix values are:- AI,AT code value in Contract class :- AI/1 (selected AI from 'prefix' field under Contract_Type) class Contract_Type(models.Model): prefix = models.CharField(default=None, blank = True, max_length=50, unique=True) main_category = models.CharField(default=None, blank = False, max_length=50) sub_category = models.CharField(default=None, blank = True, max_length=50) def __str__(self): return self.prefix class Meta: verbose_name = "Contract Type" verbose_name_plural = "Contract Type" class Contract(models.Model): def get_autogenerated_code(): last_id = Contract.objects.values('id').order_by('id').last() if not last_id: return "AI/" + str(0) return "AI/" + str(last_id['id']) code = models.CharField(max_length=10, default=get_autogenerated_code, editable=False, blank=False) nature = models.ForeignKey(Contract_Type, null=True, blank=False, verbose_name="Contract Nature") -
Reverse for 'export2' with no arguments not found
I have code identical to this but, obviously is a different view is being called. That code works but, for some reason I keep getting this error. Im new to django 2.1 so sorry if this is a simple fix. views.py def export_view(request,builddata=None): print(builddata) buildings = BuildingSearch.getBuildingString() return render(request, 'dashboard/export.html',{'buildlist': buildings,'builddata':builddata}) urls.py urlpatterns = [ path('export/<slug:builddata>/', views.export_view, name='export2'), path('export/', views.export_view, name='export'), ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) export.html var times = ($("span#stringtime").text()).replace(" ",""); window.location.href = "{% url 'export2' %}/" + times + "/"; I'm getting this error when Im trying to access localhost:8000/export/ (the 'export' url) -
How django creates internal tables dynamically for many-to-many fields
My model : class Image(models.Model): name=models.CharField(max_length=40,unique=True,help_text="name of the image") tags = models.ManyToManyField(Tag) class Tag(models.Model): tag = models.CharField(max_length=100,unique=True) here when I do makemigrations and migrate it is creating 3 tables inside my database 1.image 2.tag 3.image_tags table so, my question is i am not specifying image_tags table in my models.py file ,from where django is creating image_tags table and what is the flow ?? I have checked in migrations file but I didnot get any clarity regarding this