Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - OneToOneField Not Populating in Admin
I’m trying to get the username of the current logged in user using OneToOneField to populate in the admin once the user submits a form. The username should go in the user column of admin.py. I’ve tried various methods and still no luck. I’m new to this and this is my first Django application I’m building so I’m not sure what I’m missing. I’m stuck and have no idea what I’m doing so any help is gladly appreciated. Can someone please help? What am I missing? Thanks! Code Below: user_profile/models from django.db import models from django.urls import reverse from django.contrib.auth.models import AbstractUser, UserManager from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings from users.forms import CustomUserCreationForm, CustomUserChangeForm from users.models import CustomUser class Listing (models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) name = models.CharField(max_length=100) address = models.CharField(max_length=100) zip_code = models.CharField(max_length=100) mobile_number = models.CharField(max_length=100) cc_number = models.CharField(max_length=100) cc_expiration = models.CharField(max_length=100) cc_cvv = models.CharField(max_length=100) def create_profile(sender, **kwargs): if kwargs['user']: user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) user_profile/admin.py from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from user_profile.forms import HomeForm from user_profile.models import Listing # Register models here. class UserProfileAdmin(admin.ModelAdmin): … -
Django - Variable is not getting send with POST request
Hey im using for my django project typescript to get a specific section from a text to my view but it somehow doesnt work and I dont really know why. Here is my template in which I want the "currentgap" sent to my view after clicking on the submit button. The getSelectionText() method just sets the id 'gap' to a specific string: <form action="editorgapcreate" id=create method="POST"> <script src="../static/textselector.js"></script> <div id="app" onmouseup="getSelectionText()"> This is a test section. </div> {% csrf_token %} <b>Your current selected gap:</b> <p id="currentgap"></p> <input type="hidden" name="gap" id="currentgap"> <button type="submit" name="create_gap">Create gap</button> </form> and here is my view in which I tried calling it: def editorstart(request): if request.method == 'POST': gap = request.POST['gap'] print(gap) return render(request, 'editor_start.html') else: return render(request, 'editor_start.html') The first time using currentgap in my template it displays it correctly but trying to send it to my view with a POST request doesnt work and the print is empty and I dont really know why. -
Protect pages by raising 404
I am learning Django, and I want to protect certain pages by raising 404 if request is not from certain login user. I already foreginkey topic to user. Here is the code to protect topic page. @login_required def topic(request, topic_id): topic = Topic.objects.get(id=topic_id) if topic.owner != request.user: raise Http404 I wonder are there better ways if I want to protect a lot of pages so I don't have to add the same code in every function? -
Django - Custom User Model Username Not Populating in Admin
I’m trying to get the username of the current logged in user that submits a form from the user_profile to populate in the Django admin. The custom user model is located in the users folder & I would like that username to populate under the username field in the Django admin for user_profile. I’ve tried various methods and still no luck. I’m new to this and it’s my first Django application I’m building so I’m not sure what I’m missing. I’m stuck and have no idea what I’m doing so any help is gladly appreciated. What am I missing? Thanks! Code Below: user_profile/admin.py from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from .forms import HomeForm from users.models import CustomUser from .models import Listing # Register models here. class UserProfileAdmin(admin.ModelAdmin): model = CustomUser list_display = ['name', 'address', 'zip_code', 'mobile_number', 'created', 'updated', 'username'] list_filter = ['name', 'zip_code', 'created', 'updated', 'username'] admin.site.register(Listing, UserProfileAdmin) user_profile/models from django.db import models from django.urls import reverse from django.contrib.auth.models import User from django.db.models.signals import post_save from django.conf import settings class Listing (models.Model): username = models.CharField(max_length=100, null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) name = models.CharField(max_length=100) address = models.CharField(max_length=100) zip_code = models.CharField(max_length=100) mobile_number = models.CharField(max_length=100) … -
How to Access to Already Uploaded Docx Files in Django to search needed words?
I want to edit the needed uploaded file on webpage by searching and replacing the wanted words. How can I get the text of that doc file? I have a filefield in my models and I get the doc files in a list on my webpage,where I am able to delete the needed file or upload a new one. I try to edit the wanted uploaded doc file by creating a function in my views.py. I have tried to use docx module to open the uploaded file, and also have tried io.StringIO() but I did not manage to get the desired output. models.py class DocFile(models.Model): title = models.CharField(max_length=50) agreement = models.FileField(upload_to='') views.py def edit_file(request, upload_id): instance = get_object_or_404(DocFile, id=upload_id) content = instance.agreement.open(mode='rb') variables = [] for line in content: match = re.findall(r"\{(.*?)\}", line.text) variables.append(match) return render(request, 'uploads/file_detail.html', { 'variables': variables }) or def edit_file(request, upload_id): instance = get_object_or_404(DocFile, id=upload_id) # content = instance.agreement.open(mode='rb') content = instance.agreement(upload_id) with open(content, 'rb') as f: instance.agreement = File(f) source = io.StringIO(f) document = Document(source) variables = [] for paragraph in document.paragraphs: match = re.findall(r"\{(.*?)\}", paragraph.text) variables.append(match) for table in document.tables: for row in table.rows: for cell in row.cells: match = re.findall(r"\{(.*?)\}", cell.text) variables.append(match) source.close() … -
Trying To access a document uploaded in website created by Django . Got errors
I have some have Package not found at '/media/documents/Agreement_sample.docx' when i am trying to change the file uploaded on django Website , though i am able to access and download it . How to access the file for changing it please Help? Github link https://github.com/Arabyan/N_pr/commits/master views.py def edit_files(request, file_id): exact_file = DocFile.objects.get(id=file_id) exact_file = exact_file.document.url print(1) exact_file = Document(exact_file) print(exact_file) # r line variables = [] for paragraph in exact_file.paragraphs: match = re.findall(r"\{(.*?)\}", paragraph.text) variables.append(match) for table in exact_file.tables: for row in table.rows: for cell in row.cells: match = re.findall(r"\{(.*?)\}", cell.text) variables.append(match) print(variables) return render(request, 'edit_files.html', {'exact_file': exact_file}) edit_files.html {% block content %} <h1>Edit Document</h1> <a href="{{ exact_file }}" class="btn btn-primary btn-sm"> Download Pdf </a> <br/> <br/> <!--<button type="button">Open fields</button>--> {% endblock %} -
Django - Render is not working in my project
I am dealing with form like 1 week but couldn't solve my issue. Probably i overlook something that can be found easy by other eyes, but totally, i don't know what to do. I recognize problem by starting build form. I had to use render for form and it failed in every try. I am able to connect db and showing data in html pages but whenever i use render instead of render_to_response it is failing. And i had to use render for post request as i know. Not only for form, render is not working for all. Even for a simple: def home(request): context = {'foo': 'bar'} return render(request, 'main.html', context) models.py class ModuleNames(models.Model): ModuleName = models.CharField(max_length = 50) ModuleDesc = models.CharField(max_length = 256) ModuleSort = models.SmallIntegerField() isActive = models.BooleanField() ModuleType = models.ForeignKey(ModuleTypes, on_delete=models.CASCADE, null = True) slug = models.SlugField(('ModuleName'), max_length=50, blank=True) class Meta: app_label = 'zz' def __unicode__(self): return self.status forms.py from django import forms from MyApp.models import ModuleNames class ModuleForm(forms.ModelForm): moduleName = forms.CharField(label='Module Name', max_length=50) ModuleDesc = forms.CharField(max_length = 256) ModuleSort = forms.IntegerField() isActive = forms.BooleanField() ModuleType = forms.IntegerField() class Meta: model = ModuleNames fields =('moduleName','ModuleDesc','ModuleSort','isActive','ModuleType') view.py from django.views.generic import TemplateView from django.shortcuts import render,render_to_response, redirect from … -
Rendering forms with django-semanticui-forms and confused with how choice fields work
I'm using the module django-semanticui-forms to render my forms in a nice format with SemanticUI. I'm confused about what they're doing with choice fields and how to use it in my own code. CHOICES_1 = ( (0, "Zero"), (1, "One"), (2, "Two"), (3, "Three"), (4, "Four"), (5, "Five"), ) class Choice(models.Model): choices_1_1 = models.IntegerField(choices=CHOICES_1) When I render the form, I'm able to choose between the six options and when I output the choice on a html form like {{user.choices_1_1}}, I get an integer. This makes sense because the model has an IntegerField here. How do I get the value associated with this integer key though? Is there an easy way to print "Zero" instead of 0 without casing on each integer and rendering the string that way? Lmk if the question is confusing -
Calling function from typescript in html not working
Hey im using a django and wanted to use typescript for a specific function I need for my application. Here is my typescript file: testselector.ts: getSelectionText() { var text = ""; if (window.getSelection) { text = window.getSelection().toString(); console.log('a'); } else if (document.selection && document.selection.type != "Control") { console.log('b'); text = document.selection.createRange().text; } return text; } And here is my html where I want to call the function: {% extends "base_generic2.html" %} {% block content %} <script src="textselector.js"></script> <div id="app" onmouseup="getSelectionText()"> </div> {% endblock %} For some reason it doesnt find getSelectionText() and I dont really know why? -
django calculate duration between two timefield
I have two TimeField in a Django model that I want to calculate duration for in another databasefield, or function or class, or whatever best practice. I later want to use this information to show information sorted on 'prosjekt' and then 'aktivitet'. For example: Prosjekt1 aktivitet1 = 4 hours aktivitet2 = 2,5 hours aktivitet3 = 1 hour Prosjekt2 aktivitet1 = 5,5 hours aktivitet3 = 0,5 hours Prosjekt3 aktivitet3 = 8,5 hours etc. This is my models: from django.db import models from django.contrib.auth.models import User from prosjektregister.models import Prosjekt class Aktivitet(models.Model): aktivitet = models.CharField(max_length=100) def __str__(self): return self.aktivitet class Tid(models.Model): author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) prosjekt = models.ForeignKey(Prosjekt, on_delete=models.CASCADE) dato = models.DateField() tid_fra = models.TimeField() tid_til = models.TimeField() aktivitet = models.ForeignKey(Aktivitet, on_delete=models.SET_NULL, null=True) def publish(self): self.save() -
All accordions opening at once using Django
This is a really silly question, but I can't find the answer anywhere! I have a for loop & for each item, it creates an accordion as below. The problem is, the accordion always has the same ID, so when I toggle one to open, they all open. How can I systematically assign each a different value, so they open independently? <td colspan="5"> <div id="accordion"> <div class="card"> <div class="card-header" id="headingOne"> <h5 class="mb-0"> <button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne" aria-expanded="false" aria-controls="collapseOne"> <font color="black">Edit Task</font> </button> </h5> </div> <div id="collapseOne" class="collapse" aria-labelledby="headingOne" data-parent="#accordion"> <div class="card-body"> <form action="/update/" name="form1", id="form1" method="post"> {% csrf_token %} <div class="form-group"> <select name="assignee" class="form-control" id="exampleFormControlSelect1"> <option>Select Assignee</option> <option>kikee</option> <option>kieran</option> <option>4</option> <option>5</option> </select> </div> <div class="form-group"> <select name="priority" class="form-control" id="exampleFormControlSelect1"> <option>Select Priority</option> <option>High</option> <option>Medium</option> <option>Low</option> </select> </div> <div class="form-group"> <input type="text" name="due" class="form-control" id="task" aria-describedby="emailHelp" placeholder="Due Date YYYYMMDD"> </div> <button type="submit" name="editbutton" value={{ todo.taskid }} class="btn btn-warning">Edit Task</button> </form> </div></div></div> </div> </td> -
Django Logged in User Not Populating in Admin
I’m trying to get the current username of the current logged in user that submits this form to populate in the Django admin. I would like the username to populate under the “username” field in the Django admin. I’ve tried various methods and still no luck. This is my first Django application I’m building so I’m not sure what I’m missing. Thanks! Code Below: user_profile/admin.py from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from .forms import HomeForm from .models import Listing # Register models here. class UserProfileAdmin(admin.ModelAdmin): list_display = ['name', 'address', 'zip_code', 'mobile_number', 'created', 'updated', 'username'] list_filter = ['name', 'zip_code', 'created', 'updated', 'username'] admin.site.register(Listing, UserProfileAdmin) user_profile/models from django.db import models from django.urls import reverse from django.contrib.auth.models import User from django.db.models.signals import post_save from django.conf import settings class Listing (models.Model): username = models.CharField(max_length=100, null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) name = models.CharField(max_length=100) address = models.CharField(max_length=100) zip_code = models.CharField(max_length=100) mobile_number = models.CharField(max_length=100) cc_number = models.CharField(max_length=100) cc_expiration = models.CharField(max_length=100) cc_cvv = models.CharField(max_length=100) user_profile/forms.py import os from django import forms from django.forms import ModelForm from django.forms import widgets from django.utils import six from django.utils.safestring import mark_safe from django.utils.translation import ugettext_lazy as _ from django.template.defaultfilters import filesizeformat from avatar.conf import … -
Websocket disconnect with Channels in Django
I'm beginner with Django. I would like to use websockets with Channels. In this way I'm following this tutorial to create a simple chat. I show you my files. chat/consumers.py from channels.generic.websocket import WebsocketConsumer import json class ChatConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] self.send(text_data=json.dumps({ 'message': message })) My template file room.html : <!-- chat/templates/chat/room.html --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Chat Room</title> </head> <body> <textarea id="chat-log" cols="100" rows="20"></textarea><br/> <input id="chat-message-input" type="text" size="100"/><br/> <input id="chat-message-submit" type="button" value="Send"/> </body> <script> var roomName = {{ room_name_json }}; var chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + roomName + '/'); chatSocket.onmessage = function(e) { var data = JSON.parse(e.data); var message = data['message']; document.querySelector('#chat-log').value += (message + '\n'); }; chatSocket.onclose = function(e) { console.error('Chat socket closed unexpectedly'); }; document.querySelector('#chat-message-input').focus(); document.querySelector('#chat-message-input').onkeyup = function(e) { if (e.keyCode === 13) { // enter, return document.querySelector('#chat-message-submit').click(); } }; document.querySelector('#chat-message-submit').onclick = function(e) { var messageInputDom = document.querySelector('#chat-message-input'); var message = messageInputDom.value; chatSocket.send(JSON.stringify({ 'message': message })); messageInputDom.value = ''; }; </script> </html> Root routing configuration : # mysite/routing.py from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import chat.routing application = ProtocolTypeRouter({ # (http->django views is added … -
Display process list in Django template
I'm trying to implement the below example in Django and list all process inside a table but I have hard times to display the information in the template. >>> import psutil >>> for proc in psutil.process_iter(): ... try: ... pinfo = proc.as_dict(attrs=['pid', 'name', 'username']) ... except psutil.NoSuchProcess: ... pass ... else: ... print(pinfo) ... {'name': 'systemd', 'pid': 1, 'username': 'root'} {'name': 'kthreadd', 'pid': 2, 'username': 'root'} {'name': 'ksoftirqd/0', 'pid': 3, 'username': 'root'} I saw the pinfo object type is a dictionary and for each process a new dictionary is created containing the attributes (pid, name, username). How can I process all these separate dictionaries and display them as table rows ? -
Django admin page dependent selection lists at forms
I have 4 hierarchical groups for item categorization. I am trying to modify admin page so after i add first and second groups, third and fourth groups creation will be dependent on selection lists. Problem is I couldnt figure out how to update selection lists. My model is as follows; class FirstGroup(models.Model): first_group_definition = models.CharField(max_length=300, verbose_name="First Group") def __str__(self): return self.first_group_definition class SecondGroup(models.Model): first_id = models.ForeignKey(FirstGroup, on_delete=models.PROTECT) second_group_definition = models.CharField(max_length=300, verbose_name="Second Group") def __str__(self): return self.second_group_definition class ThirdGroup(models.Model): first_id = models.ForeignKey(FirstGroup, on_delete=models.PROTECT) second_id = models.ForeignKey(SecondGroup, on_delete=models.PROTECT) third_group_definition = models.CharField(max_length=300, verbose_name="Third Group") def __str__(self): return self.third_group_definition class FourthGroup(models.Model): first_id = models.ForeignKey(FirstGroup, on_delete=models.PROTECT) second_id = models.ForeignKey(SecondGroup, on_delete=models.PROTECT) third_id = models.ForeignKey(ThirdGroup, on_delete=models.PROTECT) fourth_group_definition = models.CharField(max_length=300, verbose_name="Fourth Group") def __str__(self): return self.fourth_group_definition I have tried ModelAdmin.formfield_for_foreignkey but couldnt succeed. Simply, in admin page when I click on add item on FourthGroup, 3 selection lists are on the form and after I choose first group field I want second group field will be updated. After I choose second group field related 3rd groups will be present in the 3 group list. -
django: ManyToMany model fileld check number of update or add using m2m signals
hear is code: class SlamQuestion(models.Model): slam = models.OneToOneField(AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True) question = models.ManyToManyField(Question) def __str__(self): return self.slam.usercode -
Django model objects do not load in Form in testing environment
Using Django 2.1.3 Getting a strange error here; I have a form multiplechoicefield that draws its choices from the values existing in a model in the database. class ChartForm(Form): P_CHOICES = tuple((p["p"], p["p"]) for p in VAR.objects.all().values("p")) p = MultipleChoiceField(widget=CheckboxSelectMultiple, choices=P_CHOICES, initial=P_CHOICES[0][1]) I am trying to run tests for a different app in the project. It throws the following error: File "/code/pyyc/forms.py", line 31, in ChartForm p = MultipleChoiceField(widget=CheckboxSelectMultiple, choices=P_CHOICES, initial=P_CHOICES[0][1]) IndexError: tuple index out of range I assumed it was just because the model objects weren't loaded. So I added in the fixtures from the VAR app. And yet, it still throws the error. Presumably, the Form is render before the test database is compiled ... ? So I am now editing the Form so that P_CHOICES is done manually, but this is obviously not ideal for the test environment. Anyone ever come across this? Is there a smart hack for this that doesn't involve commenting out lines in the Form every time you want to test? -
NoReverseMatch at /accounts/password-reset/ for Password Reset in Django
Error- In Django after submitting email in "password-reset" page, I am getting this error. NoReverseMatch at /accounts/password-reset/ Reverse for 'password_reset_done' not found. 'password_reset_done' is not a valid view function or pattern name. My Code in urls.py file- urlpatterns = [ url(r'^password-reset/', auth_views.PasswordResetView.as_view( template_name='accounts/password_reset.html'), name='password_reset'), url(r'^password-reset/done/', auth_views.PasswordResetDoneView.as_view( template_name='accounts/password_reset_done.html'), name='password_reset_done'), url(r'^password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='accounts/password_reset_confirm.html'), name='password_reset_confirm'), ] I also created separate HTML files for all pages in "accounts" directory. By the way, I am following this tutorial on youtube - click here Code Screenshot Error Screenshot -
'WSGIRequest' object has no attribute 'get', what does this mean?
I'm trying to build a simple e-mail subscription app on my django website, but I keep running into problems. The lastest is: "'WSGIRequest' object has no attribute 'get'" I've been banging my head for awhile, I have no idea what this means, any help? myproject > subscribe > forms.py: from django import forms class subscribe(forms.Form): email = forms.EmailField() name = forms.CharField(max_length=100) myproject > subscribe > views.py: from django.shortcuts import render, redirect from django.contrib import messages from .forms import subscribe as sub def subscribe(request): if request.method == 'POST': form = sub(request.POST) if form.is_valid(): form.save() name= form.cleaned_data.get('name') messages.success(request, f"Thanks for subscribing, {name}!") return redirect('home') else: form = sub(request) return render(request, "subscribe/subscribe.html", {'form':form}) myproject > subscribe > templates > subscribe > subscribe.html: {% extends "myblog/base.html" %} {% block content %} <form method='POST'> {% csrf_token %} {{ form }} <button type=submit> OK </button> </form> </div> {% endblock content %} -
Django: type object 'CategoryAttributeInlineForm' has no attribute: '_meta'
I have 2 models: Categories and CategoryAdditionalAttributes that has foreign key to Categories. Also, I'm creating an inline form set for CategoryAdditionalAttributes, but I meet this error in the testing phase: models.py class Categories(models.Model): category_breadcrumb = models.CharField(max_length=512, unique=True) class Meta: app_label = 'assortment' def __str__(self): return self.category_breadcrumb class CategoryAdditionalAttribute(models.Model): category = models.ForeignKey( Categories, on_delete=models.CASCADE, related_name='additional_attributes') attribute_key = models.CharField(max_length=500) attribute_value = models.CharField(max_length=1000) class Meta: app_label = 'assortment' def __str__(self): return "{}: {}".format(str(self.attribute_key), self.attribute_value) def __unicode__(self): return "{}: {}".format(str(self.attribute_key), self.attribute_value) admin.py class CategoryAdditionalAttributeInlineFormSet(BaseInlineFormSet): class Meta: model = CategoryAdditionalAttribute fields = ['attribute_key', 'attribute_value'] def save_new_objects(self, commit=True): saved_attributes = super( CategoryAdditionalAttributeInlineFormSet, self).save_new_objects(commit) if commit: CategoryAdditionalAttributeService() .insert_additional_attributes(saved_attributes, self.deleted_forms) return saved_attributes def save_existing_objects(self, commit=True): saved_attributes = super( CategoryAdditionalAttributeInlineFormSet, self).save_existing_objects(commit) if commit: CategoryAdditionalAttributeService() .insert_additional_attributes(saved_attributes, self.deleted_forms) return saved_attributes class CategoryAttributeInline(admin.TabularInline): model = CategoryAdditionalAttribute formset = CategoryAdditionalAttributeInlineFormSet extra = 1 class CategoriesAdmin(admin.ModelAdmin): form = CategoriesForm search_fields = ['category_breadcrumb'] inlines = [CategoryAttributeInline] test class CategoryAdditionalAttributesTest(TestCase): .... def test_insert_additional_attribute_success(self): AttributeFormSet = inlineformset_factory( Categories, CategoryAdditionalAttribute, form=CategoryAdditionalAttributeInlineFormSet) data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', 'form-0-category': self.test_category, 'form-0-attribute_key': 'a_room', 'form-0-attribute_value': 'Kamar Mandi' } test_attribute_formset = AttributeFormSet(data) self.assertEqual(test_attribute_formset.is_valid(), True) Results Traceback (most recent call last): File "/home/varian/.local/share/virtualenvs/f1-thanos- aRnD22rB/local/lib/python2.7/site-packages/mock/mock.py", line 1305, in patched return func(*args, **keywargs) File "/home/varian/Desktop/dekoruma/f1- thanos/thanos/apps/assortment/tests/test_admin.py", line 134, in test_insert_additional_attribute_success test_attribute_formset … -
Pandas groupby sum doesn't keep the other columns using Django
I have a problem using this line of code: user_metadata = user_metadata.groupby(['user_id', 'gender', 'age']).sum().reset_index() I have a dataframe with almost 120 columns, I need to keep user_id, gender and age, and then sum all the values of each column and keep all the 120 columns. I used this in jupyter and it works completely fine and it keeps all 120 columns. But I need to use it in django platform. So I use the same code in django, but it just keep 5 columns and dropped all other columns. (These 5 columns contain characters in their name while the others contain numbers.) Can someone help me please with this? -
Is there a simple way to create Chained Dynamic Drop Down List in Django Admin Site?
at this moment I am creating a project to learn how to use django. In this project there are three models: Category Subcategory Product And what I'm trying to achieve is to dynamically choose the corresponding subcategory after selecting the category, and thus be able to add the product. I tried to use smart_selects without results, since it is not compatible with python 3.7 I tried to filter the list of subcategories using the selected category field as a filter, without success, I think I am not formulating the code well, so that it takes the value of the category field to filter the list of subcategories dynamically. This is my code: /////////// //models.py """Z""" from django.db import models class Category(models.Model): """Z""" category_name = models.CharField("Name", max_length=50) class Meta: ordering = ('pk',) verbose_name = "Category" verbose_name_plural = "Categories" def __str__(self): """Z""" return self.category_name class Subcategory(models.Model): """Z""" subcategory_name = models.CharField("Name", max_length=50) subcategory_parent = models.ForeignKey( Category, verbose_name="Parent", on_delete=models.CASCADE) class Meta: ordering = ('pk',) verbose_name = "Subcategory" verbose_name_plural = "Subcategories" def __str__(self): return self.subcategory_name class Product(models.Model): """Z""" category = models.ForeignKey( Category, verbose_name="Category", on_delete=models.SET_NULL, null=True) subcategory = models.ForeignKey( Subcategory, verbose_name="Subcategory", on_delete=models.SET_NULL, null=True) product_name = models.CharField("Name", max_length=50, unique=True) class Meta: ordering = ('pk',) verbose_name = "Product" … -
Django or Laravel? which is better for my Startup [on hold]
I want to launch a startup on Android,IOS and web platforms.(I use REST API for Web Services) I want to know which one is better in terms of speed, efficiency, power and etc. Django or Laravel? I know a bit about python and php. -
Not able to load static files
I tried fetching static files for my website but nothing seems to work even the other stackoverflow answers. please help on this. settings.py - STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'static','static_root') STATICFILES_DIRS = [ os.path.join(BASE_DIR,'static','static_dirs') ] File is present in : parent_folder>static>static_dirs>css>cover.css HTML <html lang="en"> {% load staticfiles %} <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content="Aman Turate"> <title>Aman Turate - Resume</title> <link rel="stylesheet" href="{% static 'css/cover.css' %}"> -
Make the buil-in classbased view know the application namespace in Django
So,I am trying to implement password change functionality using built-in class based views(PasswordChangeView and PasswordChangeDoneView). Now, when I enter the old password, new password and confirm password fields in the built-in template and hit enter(or submit) I get a "no reverse match" error saying "Reverse for 'password_change_done' not found. 'password_change_done' is not a valid view function or pattern name." I have researched a lot and found out that its because I am using the application namespace(app_name='authenticationApp' in urls.py) thats why django is not able to find the reverse. My simple question is How do I let the built-in template know that its supposed to use namespaced URL in the reverse function ? PS: I know using my own template would resolve the issue.