Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Creating a custom admin page
I am a bit confused why my changes dont show up: I am following the official tutorial https://docs.djangoproject.com/en/3.1/intro/tutorial07/#customizing-your-project-s-templates and should override the admin base_site.html my dir structure looks like this: └───mysite ├───mysite │ └───__pycache__ ├───polls │ ├───migrations │ │ └───__pycache__ │ ├───static │ │ └───polls │ │ └───images │ ├───templates │ │ └───polls │ └───__pycache__ └───template └───admin └───base_site.html my template in settings.py like this: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], 'APP_DIRS': True, .... base_site.html contains this: .... {% block branding %} <h1 id="site-name"><a href="{% url 'admin:index' %}">mydjango</a></h1> {% endblock %} .... However, the name changes are not applied to the admin page - even after reloading. somebody has an idea why this is not working? I know that you would do it in another way as the tutorial later suggests, but to follow the tutorial it would be nice to see everything working. -
How to fix an error while loading JS file into Django?
I am making a university project in Django and when I load the JS for the responsive burger menu of the nav, it does not load properly I suppose. So the problem is that when I inspect it in chrome and check the loaded files, from the JS file which is: const navSlide = () => { const burger = document.querySelector('.burger'); const nav = document.querySelector('.nav-links') const navLinks = document.querySelectorAll('.nav-links li'); burger.addEventListener('click', () => { // toggle nav nav.classList.toggle('nav-active'); // animate links navLinks.forEach((link, index) => { if(link.style.animation) { link.style.animation = '' } else { link.style.animation = `navLinkFade 0.5s ease forwards ${index / 7 + 0.3}s`; } }); // burger animation burger.classList.toggle('toggle'); }); } navSlide(); On the event listener, it says "cannot add a property 'addEventListener' of null". Any suggestions on how to fix that? -
Iterate over 3 context variables in Django templates
Is it possible to iterate over a list of three context variables shown below so that depending on which url the user's attribute (in this instance grade, Grade 10, Grade 11, Grade 12) clicks they get the right content displayed. Current view: class SumListView(ListView): model = Summaries template_name = 'exam/summary.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['grade10'] = Summary.objects.filter(grade='Grade 10') context['grade11'] = Summary.objects.filter(grade='Grade 11') context['grade12'] = Summary.objects.filter(grade='Grade 12') return context''' Current html template block: {% block content %} {% for summary in grade10 %} <div class="container> {{ summary.content }} </div> {% endfor %} {% endblock content %} I tried this but it breaks the code since for loops and iterations are mixing: {% block content %} {% if grade10 %} {% for summary in grade10 %} <div class="container> {{ summary.content }} </div> {% endfor %} {% elif grade11 %} {% for summary in grade10 %} <div class="container> {{ summary.content }} </div> {% endfor %} {% else grade12 %} {% for summary in grade10 %} <div class="container> {{ summary.content }} </div> {% endfor %} {% enif %} {% endblock content %} What is the best way to go about this? I know I can write different urls for each context which … -
How To Solve Nested Reverse with No Arguments Found in Django
I am trying to make it so that a user can press a button to leave a review after clicking on a product/image. So I have a model that defines the top level and within that top level I allow for the option to leave a review if the user is signed in. I have been trying to troubleshoot this error for the last hour with no success. Everytime I now try to click on the product I am shown the error: Reverse for 'beaches-review' with no arguments not found. 1 pattern(s) tried: ['review/(?P[0-9]+)$'] Hopefully someone here can help me. Here is my code (P.S I am learning...): Models.py class Beach(models.Model): name = models.CharField(max_length=80) location = models.CharField(max_length=200) video = models.FileField(upload_to='beachvideo', blank=True) beachPic = models.ImageField(default='default.jpg', upload_to='beachphotos', blank=True) datetimeInfo = models.DateTimeField(auto_now=True) lat = models.FloatField() lon = models.FloatField() info = models.TextField() def average_rating(self): all_ratings = map(lambda x: x.rating, self.review_set.all()) return np.mean(all_ratings) def __str__(self): return f'{self.name}' class Review(models.Model): RATING = ( ('1', 'Avoid'), ('2', 'Not Great'), ('3', 'Decent'), ('4', 'Awesome'), ('5', 'The Best'), ) beach = models.ForeignKey(Beach, on_delete= models.CASCADE) author = models.ForeignKey(User, null=True, blank=True, on_delete= models.CASCADE) ratingRank = models.CharField(max_length= 100, blank=False, choices=RATING) waveIntensityRank = models.CharField(max_length= 100, blank=True, choices=RATING) crowdednessRank = models.CharField(max_length= 100, blank=True, choices=RATING) … -
Django filter objects by distance
Hey guys how can i filter objects by distance? Maybe anyone know a video or document about this. -
Show products of each category [wagtail]
I have just started learning wagtail. Can you tell me how to display a category name and products in that category on the page? It should look something like this: Category_name products Category_name_2 products_2 ... Category_name_N products_N Here is my code models.py class HomePage(Page): def get_context(self, request): context = super().get_context(request) context['products'] = Product.objects.child_of(self).live() context['categories'] = Category.objects.all() return context class Product(Page): sku = models.CharField(max_length=255) short_description = models.TextField(blank=True, null=True) price = models.DecimalField(decimal_places=2, max_digits=10) image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) content_panels = Page.content_panels + [ FieldPanel('sku'), FieldPanel('price'), ImageChooserPanel('image'), FieldPanel('short_description'), InlinePanel('categories', label='category'), ] class ProductCategory(models.Model): product = ParentalKey('home.Product', on_delete=models.CASCADE, related_name='categories') product_category = models.ForeignKey( 'home.Category', on_delete=models.CASCADE, related_name='products_pages') panels = [ SnippetChooserPanel('product_category'), ] class Meta: unique_together = ('product', 'product_category') @register_snippet class Category(models.Model): name = models.CharField(max_length=255, null=True) related_page = models.ForeignKey('wagtailcore.Page', null=True, blank=True, related_name='+', on_delete=models.CASCADE) panels = [ FieldPanel('name'), PageChooserPanel('related_page'), ] def __str__(self): return self.name class Meta: verbose_name = "Category" verbose_name_plural = "Categories" -
If JavaScript blocks the <textarea> tag, how does the Textfield get the value
I want to build a library for django editor (based on a great project vditor.) I read the source code of some libraries, but I was surprised to find that they all need to use to Get the value (just like this:<textarea {{ final_attrs|safe }}>{{ value }}). And vditor itself will block the tag, is there any good solution? Thank you! -
How to stop global variables from reloading when I make changes to a view in django?
I am working an a machine learning project implemented using django where i need to impute datasets for outliers and many other reasons and declare these datasets as global variables for various views to use. The problem is imputing these data sets take lot of time and each time I make a change to it is loading the project from the beginning making debugging take lot of time. Is there anyway to stop this and only apply the changes for the code i make ? -
Cannot resolve keyword 'user' into field. admin.py
im trying to override queryset in admin.py to return a queryset based on each user's group, for a model Transaction models.py class Transaction(models.Model): .... income_period_choices = (('Weekly', 'Weekly'), ('Fortnightly', 'Fortnightly')) chp_reference = models.CharField(max_length=50, unique=True) rent_effective_date = models.DateField(null=True, blank=True) income_period = models.CharField(max_length=11, choices=income_period_choices, null=True, blank=True, default='Weekly') property_market_rent = models.DecimalField(help_text='Weekly', max_digits=7, decimal_places=2, null=True, blank=True) admin.py @admin.register(Transaction) class TransactionAdmin(admin.ModelAdmin): search_fields = ['chp_reference', 'familymember__name'] inlines = [FamilyGroupInline, FamilyMemberInline] def save_model(self, request, obj, form, change): obj.user = request.user print(obj.user) super().save_model(request, obj, form, change) def get_queryset(self, request): qs = super().get_queryset(request) if request.user.is_superuser: return qs return qs.filter(user__groups__first=request.user.groups.first()) im getting the error for the last line filter query, is there any suggestions? would be so much appreciated -
Django error: unresolved import 'extra_views'
I'm trying to use extra_view Django package. I've installed it and in terminal it showed as successful and I added it to installed apps in setting.py. As I don't use virtual environment it's all installed globally, but when I try to import that package there is an unresolved import error. I use VS Code if it means something. It also happened with some other packages that I installed. Do you have any idea what is happening? -
how do I arrange toast messages with javascript
I'm working on a toast message setup where when if multiple of them are active they're not visible except the one in the front (so maybe a margin of 15px between them would help) and display them on the bottom-corner of the screen(fixed) doesn't change position when scrolling and make them disappear after 3 secs one by one. How do I go about solving this with javascript? Maybe it's possible to target "color" as in "color-green". Thx for any help! {% if messages %} {% for message in messages %} {% if message.tags == 'success' %} <div class="color-green"> <div class="color-white"> <div class="icon-success"> <i class="fas fa-check icon"></i> </div> <div class="text"> <h2>{{message}}</h2> </div> </div> </div> {% elif message.tags == 'info' %} <div class="color-blue"> <div class="color-white"> <div class="icon-info"> <i class="fas fa-info icon"></i> </div> <div class="text"> <h2>{{message}}</h2> </div> </div> </div> {% elif message.tags == 'warning' %} <div class="color-orange"> <div class="color-white"> <div class="icon-warning"> <i class="fas fa-exclamation-circle icon"></i> </div> <div class="text"> <h2>{{message}}</h2> </div> </div> </div> {% elif message.tags == 'error' %} <div class="color-red"> <div class="color-white"> <div class="icon-cross"> <i class="fas fa-times icon"></i> </div> <div class="text"> <h2>{{message}}</h2> </div> </div> </div> {% endif %} {% endfor %} {% endif %} .color-green{ bottom: 0; position: absolute; background-color: #40ff00; box-shadow: 4px … -
Django: get the percentage of tasks completed by subproject in DetailView
I have three models, srv(the main project), project(the subprojects associated with the srv model), and finally todo(tasks associated with the project model). class Srv(models.Model): srv_year = models.CharField(max_length=4) slug = AutoSlugField(populate_from = 'srv_year', always_update = True) class Project(models.Model): srv = models.ForeignKey(Srv, on_delete=models.CASCADE, null = True, blank = True) project_title = models.CharField(max_length=200, unique = True) slug = AutoSlugField(populate_from = 'project_title', always_update = True) resume = HTMLField() pub_date = models.DateTimeField(auto_now_add = True) category = models.ManyToManyField(Category) state = models.BooleanField(blank=True, null = True, default = False) weighted = models.IntegerField(blank=True, null = True) class Todo(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, null = True, blank = True) todo_title = models.CharField(max_length=200) slug = AutoSlugField(populate_from = 'todo_title', always_update = True, null = True) user = models.ForeignKey(User, on_delete=models.CASCADE, null = True, blank = True) pub_date = models.DateTimeField(auto_now_add = True) deadline_date = models.DateField(null = True) ordering_position = models.DecimalField(max_digits=5, decimal_places=2, null = True, blank = True) state = models.BooleanField(blank = True, null = True, default = False) how get the percentage of tasks completed by project, whose project is associated with a main srv? In my view class srvdetail(DetailView): model = Srv template_name = 'srv_detail.html' slug_field = 'slug' def get_context_data(self, *args, **kwargs): context = super(srvdetail, self).get_context_data(**kwargs) srv = self.get_object() srv_projects = srv.project_set.all() for … -
How to use Django template filter in for loop?
How can I filter specific field of a model in template while using for loop. code: {% for news in news_list|position:3 %} <img class="d-block w-100 rounded slideimage" style="height:415px" src="{{news.image_link}}" alt="First slide"> <h1 class="mb-2"> {{news.title}} </h1> {% endfor %} there is a 'position' field in news model,I want to get all the news that position equal 3.I tried {% for news in news_list|position:3 %} any friend can help? -
Python django django-crontab only runs once. How can I test it running the expected every minute?
I have installed django-crontab to the python virtual environment. I am attempting to add a row to a Google sheet daily, I know the function works so I just need a cron job to trigger it. Below is my folder structure: ├── api │ ├── utils │ | └── cron.py |---manage.py Here is my cron.py # For Google API to sheets import pygsheets # The ID of spreadsheet. SPREADSHEET_ID = 'abc123' def addToGraphs(): # Use service credentials print('Attempt CRON') gs = pygsheets.authorize(service_account_file='credentials.json') spreadsheet = gs.open_by_key(SPREADSHEET_ID) graphsWorksheet = spreadsheet.worksheet_by_title('Graphs') graphsWorksheet.append_table(["29/12/2020", 1, 2, 3]) return True In my settings.py I have added CRONJOBS like so: CRONJOBS = [ ('*/1 * * * *', 'utils.cron.addToGraphs') ] Using the commands that the documentation says, I am seemingly correctly adding the cron using: python manage.py crontab add . And then able to list that correctly using: python manage.py crontab show When I run it locally using: python manage.py crontab run {taskId} The function does print out "Attempt CRON" and adds the row to the Google sheet, yay! But only once... It then just ends. When I kick off the python django server with: python manage.py runserver I get no print statement and the Google doc … -
my python shows this error: Fatal error in launcher [WinError 5] because I renamed my user folder name
take note in those paths, olduser = My old user name renameduser = my new user name that I renamed from the old one I renamed my user folder name, anytime I try to use pip it shows this error Fatal error in launcher: unable to create process using '"c:\users"olduser"\appdata\local\programs\python\python39.exe" "c:\users"renameduser"\appdata\local\programs\python\python39.exe\Scripts\pip.exe" ': The system cannot find the file specified. and anytime I try to run python it shows access denied I've been trying many ways to fix this but it's not working because I renamed my user folder name somebody should please help me I beg of you -
Template Syntax Error: Could not pass the remainder
I am currently coding my first django website, and I am experiencing some troubles with the urls. Basically wrote this in my template. <div class="post-thumbnail"><a href="{{% url 'apps' 'translator' 'phrase' %}}"> Here's the urls.py path('apps/', AppsView.as_view(), name= 'apps'), path('translator/<str:phrase>/', TranslatorView.as_view(), name='translator'), When the code runs, a Template Syntax Error appears saying it couldn't parse the remainder % url 'apps' 'translator' 'phrase' %' from '% url 'apps' 'translator' 'phrase' %. I know there's something wrong with the way I wrote the url in the template. However, I don't know how to fix it. -
Use the Djongo library to connect to the AWS DynamoDB database
someone knows if you can use the Djongo library to connect to the AWS DynamoDB database. I know that the Pynamodb library can be used but it would not be connected to the django ORM Thanks. -
How to limit Django allowed username characters?
is it possible to limit the allowed special characters in Django's usernames? the default allowed characters are: Letters, digits and @/./+/-/_ I want to be: Letters, digits and ./_ Regards -
React Native image upload to Django
I am trying to upload form data, which contains images, to a Django REST backend. The issue is that the images are not being received - only the other data. The packages I am using are: apisauce (axios wrapper) corsheaders Django REST Framework React: import client from './client'; const endpoint = '/post/'; const getListings = () => client.get(endpoint); const addListing = listing => { const form = new FormData(); form.append('title', listing.title); form.append('price', listing.price); form.append('category', listing.category.value); form.append('description', listing.description); listing.image.forEach((image, index) => form.append('image', { name: 'image' + index, type: 'image/jpeg', image: image, })); const headers = { 'Content-Type': 'multipart/form-data' } console.log("form", form); return client.post(endpoint, form, {headers}); }; export default { addListing, getListings, }; The console shows the image as such: Array [ "image", Object { "image": "file:/data/user/0/host.exp.exponent/cache/ExperienceData/%25405starkarma%252Ftest1/ImagePicker/51b79c5d-709e-42db-bebe-c0cf1792f423.jpg", "name": "image0", "type": "image/jpeg", }, ], Django APIView: class PostAPIView(APIView): parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): print(request.data) file_serializer = PostSerializer(data=request.data) if file_serializer.is_valid(): file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) And the response that is printed/object created is: <QueryDict: {'title': ['dfsf'], 'price': ['123'], 'category': ['2'], 'description': ['']}> Anyone have any idea why the image will not come through? Thanks! -
Default image in django model File Field?
I want a default picture in the model file field, my code is not working. The file field is empty. file = models.FileField(upload_to='team_icons', null='True', blank='True', default='pictures/picture.png') -
I am getting an error from django send_messages() AttributeError 'str' object has no attribute send_messages()
I have no idea where to start looking for the str in send_messages(); I believe my URL path isn't configured properly but I am not getting an ImproperlyConf Url error. I have attached the code for the view the URL and the template from which I am trying to send the email #views.py def email_invite(request): profile = get_object_or_404(Profile, user=request.user) if request.method == 'POST': form = EmailInviteForm(request.POST) if form.is_valid(): cd = form.cleaned_data name = f'{cd["name"]}' subject = f'{cd["name"]} has sent you a invitation' email = f'{cd["email"]}' to = [f'{cd["to"]}'] comment = f'{cd["comment"]}' with open(str(settings.BASE_DIR.joinpath('templates/profiles/email/email_invite_message.txt'))) as f: invite_message = f.read() html_template = get_template('profiles/email/email_invite_message.html').render() msg = EmailMultiAlternatives(subject, comment, invite_message, [email], [to], name) msg.attach_alternative(html_template, "text/html") msg.send() messages.success(request, 'Your email has been sent') return redirect('home') # return HttpResponseRedirect(reverse('profiles:find_friends')) else: form = EmailInviteForm() template = 'profiles/email_invite.html' context = { 'form': form, } return render(request, template, context) The URL that I think is the root of the error #urls.py path('email-invite/', views.email_invite, name='email_invite'), #email_invite.html {% extends '_base.html' %} {% load crispy_forms_tags %} {% block extra_title %}Email an invite{% endblock extra_title %} {% block content %} <div class="container"> <h1>Send a friend an invite to join you</h1> <p class="pages-p"> Use the form to invite a friend or family member to … -
load dynamic data in html modal in Django
I have single html page with dynamic images from database in Django. I also have a modal in the same page set to invisible and opens when image is clicked. My intension is when I click on any image it should open a html model with the clicked image and its description text from db. How do I display data of the current clicked image and its description. I have tried to pass {{profile.image.url}} but this gives one information on click to all images. I didn't have to give sample code on this. -
I am trying to deploy an app to Heroku with Django_tables2 and receiving "ImportError: cannot import name 'FieldDoesNotExist' "
I have been stuck on this for days now and it is driving me crazy. I have a Django app that runs perfectly until I try to render a Django_tables2 table into the template. It works perfectly when I run on localhost but for some reason when I try to migrate or deploy to Heroku I get the following logs: (venv) home@Trevors-MacBook-Pro MHRH % heroku run python manage.py migrate Running python manage.py migrate on ⬢ medicinehatregionalhospital... up, run.1733 (Free) Traceback (most recent call last): File "manage.py", line 23, in <module> main() File "manage.py", line 19, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/app/.heroku/python/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/app/.heroku/python/lib/python3.8/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/app/.heroku/python/lib/python3.8/site-packages/django_tables2/__init__.py", line 2, in <module> from .tables import Table, TableBase, … -
Django Context Processor more than one filter
Im new to Django and python and i have the context processor below but as soon as i try to filter by one than one option it returns an empty queryset? from . models import Job from datetime import date def add_variable_to_context(request): today = date.today() jobs = Job.objects.filter(date_due__lte=today,status='Assigned') overdue = 0 for job in jobs: overdue += 1 return { 'overdue': overdue, 'jobs': jobs, } Can you pass more than one filter in a context processor like you can in a view? -
The value of 'fieldsets[4][1]' must be a dictionary
I user AbstractUser to create my custom account model in Django. Now I have a class in admins.py like so: class CustomAccountAdmin(UserAdmin): model = CustomAccount add_form = CustomAccountCreationForm fieldsets = ( *UserAdmin.fieldsets,( ('Access', {'fields': ('status', 'team', 'role')} ), ('Other', {'fields': ('phone', 'address', 'description')} ) ) ) admin.site.register(CustomAccount, CustomAccountAdmin) I want to add more fields to my custom account admin and I get this error: django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: <class 'account.admin.CustomAccountAdmin'>: (admin.E010) The value of 'fieldsets[4][1]' must be a dictionary. System check identified 1 issue (0 silenced). This format is working properly but I want to add more: fieldsets = ( *UserAdmin.fieldsets,( ('Access', {'fields': ('status', 'team', 'role')} ) ) )