Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to differentiate between modules with same name in Django
For example, there is a 'reverse' module in Django which you can use for easy navigation between links. There is also a 'reverse' module available in DRF which can be used for creating custom API endpoints easily. I'm sure people at some point need to use both the modules at different stages, but how is Django going to differentiate between these two modules? They are called almost in the same way. Or am I wrong? Maybe either of the modules can be use to carry out both the tasks? -
Dependent Nested Category in Django
I want to create 2 category 1 Main category ex a. MEN b. Woman and 2 Subcategory would be according to parent category. How I can perform these actions. class Category(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class SubCategory(models.Model): name = models.CharField(max_length=50) parent = models.ForeignKey( Category, null=True, blank=True, related_name='children', on_delete=models.CASCADE ) def __str__(self): return self.name def save(self, *args, **kwargs): # prevent a category to be itself parent if self.id and self.parent and self.id == self.parent.id: self.parent = None super().save(*args, **kwargs) class Product(models.Model): categories = models.ForeignKey( Category, related_name='products', blank=True, on_delete=models.CASCADE ) categorychild = models.ForeignKey(SubCategory, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=255) How I can solve this Im putting this question 3rd time Please help -
Separate media settings for each app in django
I am working on building a django based blog-like site, it currently has one app. It contains a media folder which contains the images uploaded by the user. However, the MEDIA_URL and MEDIA_ROOT are specified in the main settings.py file. But in the future, there will be more apps containing more media, thus I want separate MEDIA_URL(s) and settings for each app. I tried writing the MEDIA_ROOT and MEDIA_URL separately in the apps.py file, but removing this from the main settings.py file results in an error. I also tried using FileSystemStorage, but even this needed me to have a MEDIA_URLS in the settings.py file. Please let me know if you need any more details. Any help is appreciated, thanks. -
Django Email - [Errno 2] No such file or directory
I am looking to allow the user to upload and send a document via email from my django app. When I go to send the email I get the error "[Errno 2] No such file or directory:". I have tried using a relative path as well as specifying the path but I get the same error either way. I can see that the file is being successfully loaded to that location...so I feel I must be missing something obvious here. Here is my view: def email(request): if request.method == "POST": form = EmailForm(request.POST,request.FILES) if form.is_valid(): post = form.save(commit=False) # post.published_date = timezone.now() post.save() email = request.POST.get('email') subject = request.POST.get('subject') message = request.POST.get('message') document = request.FILES.get('document') email_from = settings.EMAIL_HOST_USER recipient_list = [email] email = EmailMessage(subject,message,email_from,recipient_list) base_dir = 'media' email.attach_file('Desktop/WBU2/Poseidon/media/media/'+str(document)) #also tried email.attach_file('/media/'+str(document)) email.send() else: form = EmailForm() return render(request, 'docemail.html', {'form': form}) models.py class Mails(models.Model): email = models.EmailField() subject = models.CharField(max_length=1000) message = models.CharField(max_length=20000) document = models.FileField(upload_to='media') def __str__(self): return self.email -
cleaned_data for extra fields in django ModelForms
I have the ModelForm below with an extra field named decimal_part: class MyObjectForm(forms.ModelForm): class Meta: model = MyObject exclude = [] def __init__(self, *args, **kwargs): super(MyObjectForm, self).__init__(*args, **kwargs) self.fields['decimal_part'] = forms.IntegerField( required=False, label=mark_safe('<br/>'), widget=forms.NumberInput( attrs={ 'type': 'text', 'data-type': 'number', 'placeholder': ' cm', 'maxlength': '2', })) def clean_decimal_length(self): data = self.cleaned_data['decimal_part'] return data and the template: <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <table> #...some form attr.s ...# {{ form.decimal_part}} </table> <input type="submit" value="Submit"> but after submitting the form correctly I'm getting a KeyError: 'decimal_part' data.get('decimal_part') returns None and decimal_part is not in self.cleaned_data any thoughts? thank you for you help! -
how to do Inner join using django orm
MY models.py class Forms_in_Document(models.Model): document_submit = models.ForeignKey(Document_submit, on_delete=models.CASCADE) class Document_data(models.Model): forms_in_document = models.ForeignKey(Forms_in_Document, on_delete=models.CASCADE) document_structure = models.ForeignKey(DocumentStructure , on_delete=models.CASCADE) date_created= models.DateTimeField(default=datetime.now(),null=False) string = models.CharField(null=True, max_length=100) integer = models.IntegerField(null=True) date_time = models.DateTimeField(null=True) class Application(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE, null=False) date_created = models.DateTimeField(default=datetime.now(),null=False) forms_in_document = models.ForeignKey(Forms_in_Document, on_delete=models.CASCADE, null=True) closed = models.BooleanField(default=False, null=False) new = models.BooleanField(null=False) media = models.BooleanField(default=True) Path_info = models.ForeignKey(Path_info, on_delete=models.SET_NULL,null=True) The raw sql query that i am trying to do in django is "Select * from Application app inner join Document_data dd on dd.forms_in_document=app.forms_in_document where [some filter]" How can i do this using django Thanks in Advance -
Shared authentication between Laravel and Django apps coexisting in the same domain
I have a Laravel app which contains authentication code(and a lot more including Sass subscriptions and payment gateway integration), and a Django app which contains the main routes of the application. Both of them coexist in the same domain, let's say the Laravel app resides in the /auth url and the django project resides in the / url. I want to share the authentication between the two applications, (ie) if the user logs in using a Laravel form and is redirected to the Django route, he must stay authenticated. Any suggestions and links to relevant sources will be appreciated. Forgive me if the question seems too basic. Either of the applications can't be rewritten in another , since the Laravel app has too many functionalities to be rewritten and the Django part contains some machine learning functionality -
Probrems with URLconfs in Django
I include authentication URLconf in my urls.py: path('accounts/', include('django.contrib.auth.urls')), And it urlpatterns contains this: path('login/', views.LoginView.as_view(), name='login'), path('logout/', views.LogoutView.as_view(), name='logout'), path('password_change/', views.PasswordChangeView.as_view(), name='password_change'), path('password_change/done/', views.PasswordChangeDoneView.as_view(), name='password_change_done'), path('password_reset/', views.PasswordResetView.as_view(), name='password_reset'), path('password_reset/done/', views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/<uidb64>/<token>/', views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset/done/', views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), But when I go to 127.0.0.1:8000/accounts debuger shows me this error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/accounts Using the URLconf defined in locallibrary.urls, Django tried these URL patterns, in this order: 1. admin/ 2. catalog/ 3. ^static\/(?P<path>.*)$ The current path, accounts, didn't match any of these. Why doesn't django see my URLconf? -
How to include authentication in a group of everyone in django?
How to include authentication in a group of everyone in django? for example. Main group router / (how to add group authentication here?) -- /route1 Route 1 -- /route2 Route 2 Is it easy to understand? Thank you. -
Django - Sorting posts by categories
I have two models -BlogPost and PostTopic. I would like to be able to filter by topic and see all the posts for that topic. This is working when I load up each url directly (i.e blog/cat/1), however when linking to this from the main blog post list view, I have tried the below template code: {% for topic in object_list %} <li><a href="{% url 'blog:BlogPostTopic_list' pk=topic.pk %}">{{ topic.topic }}</a></li> {% endfor %} However this doesn't work as it iterates over each topic mapped to the post (resulting in duplicates), rather than each unique topic. How do I link just to the unique topic page? models.py class PostTopic(models.Model): top_name = models.CharField(max_length=264, unique=True) def __str__(self): return self.top_name class BlogPost(models.Model): title = models.CharField(max_length=200) snippet = models.CharField(max_length=400, null=True) blog_pic = models.ImageField(upload_to='blog_pics', default='placeholder.jpg') hero_pic = models.ImageField(upload_to='blog_pics',blank=True) content = models.TextField() topic = models.ForeignKey(PostTopic, on_delete=models.CASCADE) create_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def get_absolute_url(self): return reverse("BlogPost_detail",kwargs={'pk':self.pk}) def __str__(self): return self.title views.py class BlogPostListView(ListView): model = BlogPost paginate_by = 4 def get_queryset(self): return BlogPost.objects.all().order_by('-published_date') class BlogPostDetailView(DetailView): model = BlogPost class BlogPostTopicListView(ListView): model = BlogPost template_name = 'blog/post_category.html' def get_queryset(self): return BlogPost.objects.filter(topic=self.kwargs['pk'] ) url url(r'^$',views.BlogPostListView.as_view(),name='BlogPost_list'), url(r'^(?P<pk>\d+)$',views.BlogPostDetailView.as_view(),name='BlogPost_detail'), url(r'^cat/(?P<pk>\d+)$',views.BlogPostTopicListView.as_view(), name='BlogPostTopic_list'), -
Who to display image in Django
I'm very new to Django so I saved an image into the database inside my models.py class Article(models.Model): title = models.CharField(max_length=120) content = models.TextField() active = models.BooleanField(default=True) picture = models.ImageField(upload_to='documents/pictures', null=True) now I want to display this image and I used the get_absolute_url method to get the current data from a row inside the db: def get_absolute_url(self): return f'/blog/{self.id}' In the views.py I return a renderfun with the params 'article':get_object_or_404(Article, id=my_id). Now in my template index.html I have this {% block content %} {{ article.content }} <img src="{{ article.picture }}" style="width: 200px; height: 200px;" /> {% endblock %} But if I open the developer console in chrome the img path is the same I set in models.py. The document/pictures folder is at the root of the django app. I tried to move it into the current app (Blog) but this also doesnt work. Do I have to set the media path in the settings.py ? I use django 3 and sqlite3 as db -
customize registration form in django
I created a registration form in django with blow codes forms.py: class UserFormRegistration(UserCreationForm): username = forms.CharField(label = 'نام کاربری') email = forms.EmailField(required=True, label = 'ایمیل') password1 = forms.CharField(label= 'رمزعبور', widget = forms.PasswordInput, strip = False) password2 = forms.CharField(label= 'تکرار رمز عبور', widget = forms.PasswordInput, strip = False) class Meta: model = User fields = ["username", "email", "password1", "password2"] views.py: def register(request): if request.method == "POST": form = UserFormRegistration(request.POST) if form.is_valid(): user =form.save() username = form.cleaned_data.get("username") login(request, user) messages.success(request, f"تبریک! اکانت شما با نام {username} با موفقیت ساخته شد") return redirect ("/") else: form = UserFormRegistration() return render(request, "accounts/registration.html", {"form":form}) So now, when i try to register with this form in the website i get some error like: The two password fields didn’t match. Enter a valid email address. The password is too similar to the username. How can i change these errors? For example i want to change the language and i don't want third error at all -
Using the URLconf defined in market.urls, Django tried these URL patterns
I am newbie in django. I am using DeleteView to delete the record from model but when I hit the delete button it's show me that error page not found (404) : Using the URLconf defined in market.urls, Django tried these URL patterns. I think the issue in urls.py file: from django.urls import path,include from stock.views import * from django.contrib.auth.decorators import login_required app_name='stock' urlpatterns = [ path('',login_required(StockView.as_view(), login_url='login'), name='stock'), path('login/', LoginView.as_view(), name='login'), path('signup/', SignupView.as_view(), name='signup'), path('logout',LogoutView.as_view(), name='logout'), path('addproduct/', login_required(AddProduct.as_view(), login_url='login'), name='addproduct'), path('update/<int:pk>', login_required(EditProduct.as_view(), login_url='login'), name='editproduct'), path('<int:product_id>/delete', login_required(DeleteProduct.as_view(), login_url='login'), name='deleteproduct'), ] views.py class DeleteProduct(DeleteView): model = Product success_url = reverse_lazy('stock:stock') template_name = 'stock/stock.html' Thank you! -
Django dont watch my app and TemplateDoesNotExist at /news
I think its this problem - django watching on mainApp but not on news app - django.template.loaders.app_directories.Loader: C:\Users\Name_User\Desktop\mysite\mainApp\templates\news\posts.html but i dont know how repair it, iam very new in django Directory of project ERROR TemplateDoesNotExist at /news news/posts.html, news/articles_list.html Request Method: GET Request URL: http://127.0.0.1:8000/news Django Version: 3.0.4 Exception Type: TemplateDoesNotExist Exception Value: news/posts.html, news/articles_list.html Exception Location: C:\Users\Victor.INC\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\loader.py in select_template, line 47 Python Executable: C:\Users\Victor.INC\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.4 Python Path: ['C:\\Users\\Victor.INC\\Desktop\\mysite', 'C:\\Users\\Victor.INC\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip', 'C:\\Users\\Victor.INC\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs', 'C:\\Users\\Victor.INC\\AppData\\Local\\Programs\\Python\\Python37-32\\lib', 'C:\\Users\\Victor.INC\\AppData\\Local\\Programs\\Python\\Python37-32', 'C:\\Users\\Victor.INC\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages', 'C:\\Users\\Victor.INC\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages\\south-1.0.2-py3.7.egg'] Server time: Sun, 29 Mar 2020 12:20:58 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.app_directories.Loader: C:\Users\Victor.INC\Desktop\mysite\mainApp\templates\news\posts.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Victor.INC\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\admin\templates\news\posts.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Victor.INC\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\auth\templates\news\posts.html (Source does not exist) Using engine django: django.template.loaders.app_directories.Loader: C:\Users\Victor.INC\Desktop\mysite\mainApp\templates\news\articles_list.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Victor.INC\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\admin\templates\news\articles_list.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Victor.INC\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\auth\templates\news\articles_list.html (Source does not exist) Traceback Switch to copy-and-paste view C:\Users\Victor.INC\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py in inner response = get_response(request) … ▶ Local vars C:\Users\Victor.INC\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py in _get_response response = self.process_exception_by_middleware(e, request) … ▶ Local vars C:\Users\Victor.INC\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py in _get_response response = response.render() … ▶ Local vars C:\Users\Victor.INC\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\response.py in render self.content = self.rendered_content … ▶ Local vars C:\Users\Victor.INC\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\response.py in rendered_content template = self.resolve_template(self.template_name) … ▶ Local vars C:\Users\Victor.INC\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\response.py in resolve_template return select_template(template, using=self.using) … -
Heroku app having Mysql database on CleasDB very slow
I have uploaded my MySql data base to a ClearDb server since then, the website (which right now is running locally and is not uploaded yet ) is super slow! I even upgraded the ClearDb account by still , very slow does someone have a solution ? thanks -
How to Upgrade to the latest version of Django
The current version of python which is currently running in my system is 3.7.4 while the django is 1.11 due to which i recieve alots of errors , can someone explain how to Upgrade Django to the Latest version ?? -
Django transform lat lon models to one pointfield and serialize it via geojson
My model # GPS latitudes latitudine = models.FloatField(max_length=50,default=None) # GPS longitude longitudine = models.FloatField(max_length=50,default=None) # GEOJson point = models.PointField(srid=4326, geography=True, null=True) is there any way to create or pass lat long data to GEOjson model? "features": [ { "type": "Feature", "properties": { "latitudine": "45.0717383", "longitudine": "7.6810848" }, "geometry": null }, so all data from feature will go to geometry field? -
python manage.py makemigrations does not work on Heroku
The project runs fine on my localhost, but when I try to deploy iron Heroku, it does not detect the AbstracBase user model. It creates the Profile model but when I try to migrate the changes it throws a Makekigrations (venv) C:\Users\KIIT\Documents\Django\Touch>heroku run python manage.py makemigrations Running python manage.py makemigrations on ⬢ api-touch... up, run.1133 (Free) Migrations for 'account': account/migrations/0001_initial.py - Create model Profile Migrations for 'questions': questions/migrations/0001_initial.py - Create model Question Migrations for 'answers': answers/migrations/0001_initial.py - Create model Answer Migrate (venv) C:\Users\KIIT\Documents\Django\Touch>heroku run python manage.py migrate Running python manage.py migrate on ⬢ api-touch... up, run.7280 (Free) Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/loader.py", line 166, in check_key return self.graph.root_nodes(key[0])[0] IndexError: list index out of range During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 86, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 18, … -
django.docutils.six module not found in heroku
this is my firtime deploying to heroku cloud and when i deployed it wont just load, gunicorn and procfile everything is right. If someone can help to fix it, it will be so much appreciated. i think the error is related to django utils six whose provision was dropped fromdjango3 but dont know any way to fix that myself. 2020-03-29T12:01:12.508961+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 35, in load_middleware 2020-03-29T12:01:12.508961+00:00 app[web.1]: middleware = import_string(middleware_path) 2020-03-29T12:01:12.508961+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/module_loading.py", line 17, in import_string 2020-03-29T12:01:12.508962+00:00 app[web.1]: module = import_module(module_path) 2020-03-29T12:01:12.508962+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module 2020-03-29T12:01:12.508962+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2020-03-29T12:01:12.508963+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 994, in _gcd_import 2020-03-29T12:01:12.508963+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 971, in _find_and_load 2020-03-29T12:01:12.508963+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked 2020-03-29T12:01:12.508964+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 665, in _load_unlocked 2020-03-29T12:01:12.508964+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 678, in exec_module 2020-03-29T12:01:12.508964+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed 2020-03-29T12:01:12.508964+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/whitenoise/middleware.py", line 10, in <module> 2020-03-29T12:01:12.508965+00:00 app[web.1]: from django.utils.six.moves.urllib.parse import urlparse 2020-03-29T12:01:12.508971+00:00 app[web.1]: ModuleNotFoundError: No module named 'django.utils.six' 2020-03-29T12:01:12.509454+00:00 app[web.1]: [2020-03-29 12:01:12 +0000] [10] [INFO] Worker exiting (pid: 10) 2020-03-29T12:01:12.638899+00:00 app[web.1]: [2020-03-29 12:01:12 +0000] [12] [ERROR] Exception in worker process 2020-03-29T12:01:12.638902+00:00 app[web.1]: Traceback (most … -
Django prefetch_related() in ListView class based view
I have a simple blog with 2 models: one for Post and one for Comment, like so: class Post(models.Model): title = models.CharField(max_length=100) # content = models.TextField() content = RichTextUploadingField(blank=True, null=True, config_name='claudiu_cfg') date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Comment(models.Model): author = models.CharField(max_length=20) text = models.TextField(max_length=350) date_posted = models.DateTimeField(default=timezone.now) post = models.ForeignKey(Post, on_delete=models.CASCADE) def __str__(self): return self.author I want to display all posts (paginated) and how many comments each have. My views.py: class PostListView(ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 Just like this i was getting all posts, but now i want to access the Comment table with as little selects as possible. I know one way to do this is define a queryset and did it like this: class PostListView(ListView): model = Post template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 querryset = Post.objects.all().prefetch_related() However that does not access the Comment data. Then i tried to overrite the get_queryset() function hopping to get the desired result. Still no success. def get_queryset(self): posts = Post.objects.all().prefetch_related('pk__comment').all() comments = Comment.objects.all().prefetch_related('post') print(dir(posts)) print('---------------------') print(posts._prefetch_done) return posts.order_by('-date_posted') That still … -
iterating over <class 'django.http.request.QueryDict'>?
i am sending a post request via ajax to the django's backend. When i print the respnse using print(type(request.POST)) the output is () . now i want to type cast it in dictionary and then iterate through it. def checkoutnow(request): dict_items = {} p = 0 if request.method == 'POST': print(type(request.POST)) m = request.POST print(dict(m)) m = dict(m) print(m['object[0][name]']) print(len(m)) m.pop('csrfmiddlewaretoken') print(len(m)) for i in range(int(len(m)/5)): dict_items = {i : {'name':f"object[{i}][name]", 'qty': f"object[{i}][qty]"}} p = len(m)/5 print(dict_items) return render(request, "mart/checkout.html") when i typecasted it in dict()... the output is : {'object[0][name]': ['new5'], 'object[0][id]': ['5'], 'object[0][price]': ['888'], 'object[0][qty]': ['7'], 'object[0][category]': ['new arrival'], 'csrfmiddlewaretoken': ['lkPPM58fYxegavTCAz75mN5EiFvynjIr27khr78AYdQRIb49nhT4YFjcTuuVwlLb']} therefore i pop the last item and then iterate it using f string but the problem is with the output: {0: {'name': 'object[0][name]', 'qty': 'object[0][qty]'}} Looks like the keys that i am iterating via f strings are not putting the values...how can i iterate through it? -
Extending a ModelForm with a ForeignKey field that was previously excluded
I have the following model: class Watchman(models.Model): group = models.ForeignKey('groups.Group') name = models.CharField(max_length=64) And the following model form: class NewWatchmanForm(forms.ModelForm): class Meta: model = Watchman fields = ['name'] At the time the new Watchman is created, I do not know which group it belongs to, hence name is the only model field defined in NewWatchmanForm. However, once I do figure out the correct group it belongs to, I use this form to update the object with the appropriate group: class UpdateWatchmanForm(NewWatchmanForm): group = forms.ModelChoiceField(queryset=Group.objects.all()) class Meta(NewWatchmanForm.Meta): fields = NewWatchmanForm.Meta.fields + ("group",) I was curious if there might be a better way to reuse my NewWatchmanForm. Ideally, I'd like to avoid having to declare the group explicitly, something like this: class UpdateWatchmanForm(NewWatchmanForm): # group = forms.ModelChoiceField(queryset=Group.objects.all()) class Meta(NewWatchmanForm.Meta): fields = NewWatchmanForm.Meta.fields + ("group",) However, if I do that, I get this error: fields = NewWatchmanForm.Meta.fields + ("group",) TypeError: can only concatenate list (not "tuple") to list What is the correct way to subclass an existing ModelForm and include a ForeignKey field (without redefining forms.ModelChoiceField(...))? -
How to get current logged in user using django-microsoft-auth for Microsoft authentication?
I was following this guide to implement Microsoft authentication for my django app (https://django-microsoft-auth.readthedocs.io/en/latest/usage.html) using the django-microsoft-auth package. I just don't understand how I can get the currently logged in user id/email after the user has successfully logged in as the guide does not cover this? -
How to fix NoReverseMatch at /delete_order/1/
and always show this error: Reverse for 'delete_order' with arguments '('',)' not found. 1 pattern(s) tried: ['delete_order/(?P<pk>[0-9]+)/$'].whereas my urls.py file is given below my urls from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.Home, name = 'home'), path('products/', views.Products, name = 'products'), path('customers//', views.Customers, name = 'customers'), path('create_order//', views.CreateOrder, name = 'create_order'), path('update_order//', views.UpdateOrder, name='update_order'), path('delete_order//', views.deleteorder, name='delete_order'), ] create order file html {% extends 'accounts/main.html' %} {% load static %} {% block content %} {% csrf_token %} {{ formset.management_form }} {% for form in formset %} {{form}} {% endfor %} {% endblock %} my models which are given below from django.db import models class Customer(models.Model): name = models.CharField(max_length=100, null=True) phone = models.CharField(max_length=100, null=True) email = models.CharField(max_length=100, null=True) created_date = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name class Tags(models.Model): name = models.CharField(max_length=100, null=True) def __str__(self): return self.name class Product(models.Model): CATEGORY = ( ('Indoor', 'Indoor'), ('Outdoor', 'Outdoor') ) name = models.CharField(max_length=100, null=True) price = models.FloatField( null=True) category = models.CharField(max_length=100, null=True, choices=CATEGORY) description = models.CharField(max_length=200, null=True) created_date = models.DateTimeField(auto_now_add=True, null=True) tags = models.ManyToManyField(Tags) def __str__(self): return self.name class Order(models.Model): STATUS = ( ('Pending', 'Pending'), ('Out for Delivery', 'Out for Delivery'), ('Delivered', 'Delivered'), ) … -
Django ORM: adding counter for all subclasses to (abstract) parent class
I am working on a restaurant app. I have different dish type classes (Pizza, Platter, etc) and in order to pass a dict or list (JSON-format) of ALL dishes to the JS-client, I was thinking of adding an (abstract) parent class Dish that would contain a counter or ID that identifies every dish (the aim being I can then use those ID's to access a large number of input fields and respective IDs in the html-form from the menu-page). Any ideas on the best way to do this? I tried using InheritanceManager(), but that doesn't work if my Dish class is abstract. If it is not abstract (which it should be, I'd say), I get a You are trying to add a non-nullable field 'dish_ptr' error. Not sure my whole approach even makes sense, but can't think of a better way to work with large HTML-forms with 50-100 input fields (menu items).