Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using django model in django template javascript json error
I want to use django model in template javascript and people say I need to make it into json and then pass it so I made json object from models.py and views.py like this. models.py from django.db import models from django.utils.timezone import localdate class Posts(models.Model): address = models.CharField(max_length=100, null=True) lat = models.CharField(max_length=50, null=True) lng = models.CharField(max_length=50, null=True) name = models.CharField(max_length=50, null=True) title = models.CharField(max_length=50, null=True) pick_date = models.DateField(null=True) create_date = models.DateField(auto_now=True, null=True) music = models.CharField(max_length=100, null=True) mood = models.CharField(max_length=50, null=True) description = models.CharField(max_length=300, null=True) image = models.ImageField(upload_to="images/", null=True) # H E R E # def to_json(self): return { "address": self.address, "lat": self.lat, "lng": self.lng, "name": self.name, } def __str__(self): return str(self.title) views.py import json def post_list(request): posts = Posts.objects.all() context = { "posts": posts, "posts_js": json.dumps([post.to_json() for post in posts]), } return render(request, "posts/map_marker.html") map_marker.js // this js file is linked to map_marker.html let posts = JSON.parse("{{ posts_js | escapejs }}"); console.log(posts); I want to see how the posts object looks like but it keeps saying json error JSON.parse: expected property name or '}' at line 1 column 2 of the JSON data It's hard to find a reason as I can't look through how the json object looks like. … -
Perform action from a form or link without refreshing the page/view with django
I'm developing a project where I need to add members to a group, for that, I go through all registered members and present them in my html template. Each member has the "add" button next to it, but always when doing this it refreshes a page... I would like to know how to do this without needing to refresh, ie click on add and it is already added automatically. views.py def add_members(request, id): plan=Plan.objects.get(id=id) users = User.objects.all() # extended django's default user model return render(request,'site/add_members.html', {'plan':plan, 'users':users}) add_members.html {% extends 'base.html' %} {% block title %} Add Members {%endblock%} {% block content %} <div class="row"> {% for i in users %} <h4>{{i.first_name}}</h4> <form method="POST"> {% csrf_token %} <input type="submit">Add</input> </form> {%endfor%} </div> {%endblock%} -
css is not working in my blog page only other pages working properly in my django project
I am working on a django project. All css working well on my local server but when i am hosting on pythonanywhere.com then css of only /blog url not working properly. I can't able to find the error. Please help me. You can visit my hosted website at http://sauravportfolio.pythonanywhere.com/blog/ and you can see my entire code at github https://github.com/saurav389/portfolio . you can see my all css code at portfolio/src/portfolio/static/css/ folder. and my bootstrap is not working in chrome browser too. Please do something for me. -
Django filter Logging to slack channel
I am trying to implement a function to filter the error message that sent to Slack channel. I still want it to log in .log file just dont want it sent it out to Slack. This is what i have tried so far: def contains_url(record): if 'abc' in record.request.path: return False return True LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '[{levelname}] {asctime} {module} {process:d} {thread:d} {message}', 'style': '{', }, 'simple': {'format': '[{levelname}] -- : {message}', 'style': '{',}, }, 'filters': { 'contains_url': { '()': 'django.utils.log.CallbackFilter', 'callback': contains_url, } }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple', }, 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'log.log', 'formatter': 'simple', }, 'slack_admins': { 'level': 'ERROR', 'filters': ['contains_url'], 'class': 'django_slack.log.SlackExceptionHandler', }, }, 'loggers': { 'django': { 'handlers': ['console', 'file', 'slack_admins'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'), } } so basically, i would want all the error message from an url that contain 'abc' log to the log.log as usual but just not want it in slack channel. I added slack_admins -> filters but it didn't help. Any suggestions ? Thanks -
Getting an error when attempting to run my utility script
I am trying to build a database load utility for my project. The old application is running and has MySQL dB records that I want to import into the Django mysql instance. I started writing a script and was able to connect to my old (outside of Django) DB just fine, but wanted to use the models in my new Django project so that I can create objects and use the save routines/methods etc. Just in the beginning stages, but when I attempt to import the models from my Django site in my new utility app, it says module not found...? Am I missing something? I did a python manage.py startapp db_load to create my app. The code resides there in a file named db_load.py. Here is what it looks like: #!/usr/bin/env python ################################ # This utility will load old records from a Production db # stored in local host into the Django database on local host # ################################ import MySQLdb from trackx_site.models import Program db_old_trackx = MySQLdb.connect( host= "localhost", db = "old_db", user = "root", passwd = "blah blah", charset='utf8mb4') db_django_db = MySQLdb.connect( host = "localhost", db = "new_project_blah", user = "root", passwd = "blah") sql = "select ......" … -
ModuleNotFoundError: No module named 'music_controller.api'
When I run the server, I am getting the following error: from music_controller.api.models import Room ModuleNotFoundError: No module named 'music_controller.api' I think the problem is from the import in the views.py: from django.shortcuts import render from rest_framework import generics from .serializers import RoomSerializer from .models import Room # Create your views here. class RoomView(generics.CreateAPIView): queryset = Room.objects.all() serializer_class = RoomSerializer I made sure that the app name is included in INSTALLED_APPS in the settings.py. The following is the tree of my project: -
How to get just the relational fields of a model?
Here is my model, the question is below. from django.db import models # ... class County(models.Model): name = models.CharField(max_length=50, verbose_name=_("Numele județului")) capital = models.ForeignKey("Municipality", on_delete=models.PROTECT, null=True, blank=True, related_name="capital_of", verbose_name=_("Reședința")) region = models.ManyToManyField(Region, related_name="counties", verbose_name=_("Regiunea")) area = models.IntegerField(verbose_name=_("Suprafața")) population = models.IntegerField(verbose_name=_("Populația")) description = models.TextField(verbose_name=_("Descrierea")) north = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True, related_name="to_south", verbose_name=_("Nord")) northeast = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True, related_name="to_southwest", verbose_name=_("Nord-est")) east = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True, related_name="to_west", verbose_name=_("Est")) southeast = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True, related_name="to_northwest", verbose_name=_("Sud-est")) south = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True, related_name="to_north", verbose_name=_("Sud")) southwest = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True, related_name="to_northeast", verbose_name=_("Sud-vest")) west = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True, related_name="to_east", verbose_name=_("Vest")) northwest = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True, related_name="to_southeast", verbose_name=_("Nord-vest")) class Meta: verbose_name = _("Județ") verbose_name_plural = _("Județe") def __str__(self): return self.name @property def neighbours(self): neighbour_counties = {} for field in self._meta.fields: if field.related_model == County: neighbour_counties[field.name] = field return neighbour_counties neighbours.fget.short_description = _("Vecinii") In this example I want to add two instances: Olt and Teleorman. If I create Olt and specify Teleorman as its eastern neighbour, how can I automatically set the western neighbour of Teleorman to Olt? My idea was to get a list with the eight neighbour fields as a property and it works fine until I try to get … -
How to prevent "Frame load interrupted" Safari browser console error upon form-initiated download?
I have tried all the answers I could find regarding this Safari browser console error: Failed to load resource: Frame load interrupted and so far, none of the suggestions have prevented the error. To summarize, I have an advanced search page that presents search results on the same page as the search form. When there are results, I include a separate download form (with a hidden element containing the DB query (in the form of JSON) and a visible button named "Download". There are 2 classes involved: the advanced search class (AdvancedSearchView) and the advanced search download class (AdvancedSearchTSVView). The download works. So all I want to do is prevent the error from appearing in the browser console. Here are the snippets that I believe are relevant: views.py class AdvancedSearchView(MultiFormsView): template_name = "DataRepo/search_advanced.html" download_form = AdvSearchDownloadForm() ... def form_valid(self, formset): download_form = AdvSearchDownloadForm(initial={"qryjson": json.dumps(qry)}) return self.render_to_response(self.get_context_data( ... download_form=download_form)) class AdvancedSearchTSVView(FormView): form_class = AdvSearchDownloadForm template_name = "DataRepo/search_advanced.tsv" content_type = "application/text" success_url = "" basv_metadata = BaseAdvancedSearchView() def form_valid(self, form): cform = form.cleaned_data qry = json.loads(cform["qryjson"]) now = datetime.now() dt_string = now.strftime("%d/%m/%Y %H:%M:%S") filename = (qry["searches"][qry["selectedtemplate"]]["name"] + "_" + now.strftime("%d.%m.%Y.%H.%M.%S") + ".tsv") res = performQuery(qry, q_exp, self.basv_metadata.getPrefetches(qry["selectedtemplate"])) response = self.render_to_response(self.get_context_data(res=res, qry=qry, dt=dt_string, … -
How to get a DateTime picker on clear django?
I need to have a picker for DateTimeField, but I dont realy know how to do it. Ive tried admin widget but I think I did it wrong. The closest thing to a solution was: models.py class MyModel(models.Model): myfield = models.DateTimeField() forms.py class MyModelForm(forms.ModelForm): class Meta: widgets = {'myfield': widgets.SplitDateTimeWidget( date_attrs={'type': 'date'}, tame_attr={'type': 'time'})} It shows me a working picker, but when i try to press a save button it says me an error about method 'strip' (forgot actual error, sry). -
HTML forloop - double
I am in my HTML file for my website. The first forloop checks to see what account the user is logged into and then only displays that user's data and it works perfectly on its own. {% for item in user.Doc.all %} The second forloop loops through all the data that "__stratswith"Title: " and displays it and this works perfectly on its own. {% for post in templates %} I am using Django and python to build the website and once running into this problem I have researched if there is any other way to loop through the forloops in a different location like my views.py file and I have had no luck. I need to do it in the HTML but when I write this... {% for item in user.Doc.all %} {% for post in item.templates %} {{ post.content }} {% endfor %} {% endfor %} It doesn't work. It indicated that there is data trying to be displayed because I have an if statement before the for-loops but no data is displayed. I need the proper way to write a nested forloop in an HTML file properly and I cant figure it out. The example I have should … -
Django - How to create ManyToMany relations with "through" and "to"?
I have 3 models to create a proper relation between a Genre and a Movie object. In addition I also have MovieGenre model to glue Movies and Genre model together: class Genre(models.Model): objects = RandomManager() id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(verbose_name=_("Genre"), blank=True, null=True, editable=False, unique=True, max_length=50) class Movies(models.Model): ... id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) genre_relation = models.ManyToManyField(through='MovieGenre', to='Genre') class MovieGenre(models.Model): movie = models.ForeignKey(Movies, on_delete=models.CASCADE) genre = models.ForeignKey(Genre, on_delete=models.CASCADE) I have noticed that if I create new genre objects and there relations like so: def pull_genre(object_id): if genre_value: object_genre = genre_value.split(", ") for genre in object_genre: new_genre, create = object_id.genre_relation.get_or_create( name=genre, movies=object_id ) I get many times the same "name" under a different "id" at my "Genre" model where I basically only need the name once. For example name=Comedy is present under many different ID's ... Why that? I also tried unique=True at the name field but running into: django.db.utils.IntegrityError: (1062, "Duplicate entry 'Drama' for key 'App_genre_name_b25416d5_uniq'") How can I create the relation without this strange flaw? In the end I only need "name" at "Genre" model once and the relation between one "Movie" and multiple "Genre" trough the MovieGenre model. Thanks in advance -
Display a Boolean field result if it's True
I'm having trouble here to display the return of a boolean field in the template. I need to display the name of the field if it is true in the template. Any help will be welcome. models ´´´ class IEIS(Model.models): topo = models.BooleanField() ´´´ views def view_ieis(request, pk): ieis = IEIS.objects.get(pk=pk) return render(request, 'ieis/view.html', {'ieis': ieis,}) template.html <div table class="table table-reponsive"> <table class="table table-bordered"> <thead> <tr> <th scope="col">Tipo</th> </tr> </thead> <tbody> <tr> <td> {% if topo is True %} <p>Topo</p> {% endif %} </td> </tr> </tbody> </table> </div> -
AttributeError: type object ' ' has no attribute 'object'
I'm learning python and follow step by step the book "Learning python" Eric Metiz. I am so confused, I had checked the code a few times and it exactly the same as in the book. Could you help me out with this? in models.py from django.db import models class Topic(models.Model): # Тема, которую изучает пользовательн text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) objects = models.Manager() def __str__(self): # Возвращает строковое представление модели return self.text class Entry(models.Model): # Информация, изученная пользователем по теме topic = models.ForeignKey(Topic, on_delete=models.CASCADE) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'entries' def __str__(self): if len(self.text) > 50: return self.text[:50] + "..." else: return self.text in views.py from django.shortcuts import render from .models import Topic # Create your views here. def index(request): # Домашняя страница Learning_log return render(request, 'learning_logs/index.html') def topics(request): # Выводит список тем topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) def topic(request, topic_id): # Выводит одну тему и все ее записи topic = Topic.object.get(id=topic_id) entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, 'entries': entries} return render(request, 'learning_logs/topic.html', context) The stacktrace: [21/Jul/2021 15:12:05] "GET / HTTP/1.1" 200 396 [21/Jul/2021 15:12:06] "GET /topics HTTP/1.1" 200 352 Internal Server Error: /topics/1/ Traceback (most recent … -
Django - Why is this TableView not ordering the queryset?
I have a TableView in a Django project which isn't properly ordering its queryset. I tried adding the ordering to the model Meta, overriding the view's get_queryset method, and don't know how best to tackle this. This doesn't happen in any other view, I have many views with many different models, and usually overriding the "get_queryset" method works fine, and I can order however I need there, but right now it isn't working in this particular view. The view looks like this: class ShippingCenterPricesTableView(PurchaseViewingPermissionMixin, PagedFilteredTableView): model = ShippingCenterPriceHistory table_class = ShippingCenterPricesTable template_name = 'purchases/shipping_center/shipping_center_prices_table.html' filter_class = ShippingCenterPriceFilter export_name = "PreciosCentrosDeEmbarque" formhelper_class = ShippingCenterPriceFormHelper paginate_by = 100000000 def get_context_data(self, **kwargs): context = super(ShippingCenterPricesTableView, self).get_context_data(**kwargs) context['allows_shipping_center_creation'] = self.request.user.purchases_permission == '2' return context def get_queryset(self, **kwargs): qs = super(ShippingCenterPricesTableView, self).get_queryset() qs = qs.order_by('-date') return qs The model looks like this: class ShippingCenterPriceHistory(models.Model): shipping_center = models.ForeignKey(ShippingCenter, on_delete=models.SET_NULL, null=True, blank=False, verbose_name='Centro de embarque') circular_price = models.FloatField(verbose_name='Precio circular sin I.V.A.', null=False, blank=False) differenced_price = models.FloatField(verbose_name='Precio diferenciado', null=False, blank=False) date = models.DateField(verbose_name='Fecha actualización', auto_now_add=True) observations = models.CharField(verbose_name='Observaciones', max_length=100, null=True, blank=True) current = models.BooleanField(verbose_name='Precio actual', default=True) @property def discount_percentage(self): return 1 - (self.differenced_price / self.circular_price) class Meta: ordering = ('-date',) And, in case it's relevant, the Table looks … -
ERROR RUN pip install -r requirements.txt when using docker-compose up
How should I create and install the requirements.txt file in order to be able to read it properly when running docker-compose up? Problems when running docker-compose up with the requirements.txt created via pip freeze > requirements.txt requirements.txt: certifi==2021.5.30 charset-normalizer==2.0.3 Django==2.2.5 django-cors-headers==3.7.0 django-rest-framework==0.1.0 djangorestframework==3.12.4 idna==3.2 psycopg2 @ file:///C:/ci/psycopg2_1612298715048/work python-decouple==3.4 pytz @ file:///tmp/build/80754af9/pytz_1612215392582/work requests==2.26.0 sqlparse @ file:///tmp/build/80754af9/sqlparse_1602184451250/work urllib3==1.26.6 wincertstore==0.2 I use anaconda and pip to install packages The Dockerfile for the backend of my app tries to RUN pip install -r requirements.txt rising the following errors. I could sense the @ packages arise error, but the strangest for me is the first one (#17 1.299) since it seems to be focusing on python-decouple==3.4 as just python. => ERROR [... 4/5] RUN pip install -r requirements.txt 1.8s ------ > [... 4/5] RUN pip install -r requirements.txt: #17 1.299 DEPRECATION: Python 3.4 support has been deprecated. pip 19.1 will be the last one supporting it. Please upgrade your Python as Python 3.4 won't be maintained after March 2019 (cf PEP 429). #17 1.345 Collecting certifi==2021.5.30 (from -r requirements.txt (line 1)) #17 1.515 Collecting charset-normalizer==2.0.3 (from -r requirements.txt (line 2)) #17 1.541 Could not find a version that satisfies the requirement charset-normalizer==2.0.3 (from -r requirements.txt … -
Django How to capture a C2B Transaction in Django
I want to capture transactions made to my till number directly (Not those paid via STK push) so that I can save them to database. How do I go about it. I am using django -
how can i delete my comment in with a delete function or class in Django?
how can I create a delete function or class to delete a comment with this detail? this is part of my comment model in the comment app class Comment(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='comments') content = models.TextField() parent = models.ForeignKey('self', null=True, blank=True, related_name='replies', on_delete=models.CASCADE) this is part of my view in product app def product_detail(request, *args, **kwargs): selected_product_id = kwargs['productId'] product = Product.objects.get_by_id(selected_product_id) if product is None or not product.active: raise ("not valid") comments =product.comments.filter(active=True, parent__isnull=True) new_comment=None if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): parent_obj = None try: parent_id = int(request.POST.get('parent_id')) except: parent_id = None if parent_id: parent_obj = Comment.objects.get(id=parent_id) if parent_obj: replay_comment = comment_form.save(commit=False) replay_comment.parent = parent_obj new_comment = comment_form.save(commit=False) new_comment.product = product new_comment.save() else: comment_form = CommentForm() -
Unable to use runserver_plus for django
I am using the command to run my python-django project on https "python3 manage.py runserver_plus 0.0.0.0:9999 --cert-file /path/to/cert/app" but I get the error File "/Users/xyz/django_dev_portal/django-api-1/app/manage.py", line 16 ) from exc ^ SyntaxError: invalid syntax I have django-extensions installed. Im unable to figure out whats going wrong as Im very new to Django and Python. Any help is greatly appreciated. Cheers, Sheetal -
attribute error in django. django.db.models has no attribute
I am trying to write the code so that a user in the system can view complaint registered by others on this page but not their own complaints. This is the code, but I don't understand what's wrong: views.py: class OtherPeoplesComplaints(TemplateView): model = Complaint form_class = ComplaintForm template_name = 'userComplaints.html' def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context["complaints"] = models.Complaint.objects.exclude( profile__user = self.request.user ) models.py: class Complaint(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) id = models.AutoField(blank=False, primary_key=True) reportnumber = models.CharField(max_length=500 ,null = True, blank= False) eventdate = models.DateField(null=True, blank=False) event_type = models.CharField(max_length=300, null=True, blank=True) device_problem = models.CharField(max_length=300, null=True, blank=True) manufacturer = models.CharField(max_length=300, null=True, blank=True) product_code = models.CharField(max_length=300, null=True, blank=True) brand_name = models.CharField(max_length = 300, null=True, blank=True) exemption = models.CharField(max_length=300, null=True, blank=True) patient_problem = models.CharField(max_length=500, null=True, blank=True) event_text = models.TextField(null=True, blank= True) document = models.FileField(upload_to='static/documents', blank=True, null=True) def __str__(self): return self.reportnumber forms.py: class DateInput(forms.DateInput): input_type = 'date' class ComplaintForm(ModelForm): class Meta: model = Complaint fields = '__all__' widgets = { 'reportnumber': forms.TextInput(attrs={'placeholder': 'Report number'}), 'event_type': forms.TextInput(attrs={'placeholder': 'Event type'}), 'eventdate': DateInput(), 'device_problem': forms.TextInput(attrs={'placeholder': 'Device Problem'}), 'event_text': forms.Textarea(attrs={'style': 'height: 130px;width:760px'}), 'manufacturer': forms.TextInput(attrs={'placeholder': 'Enter Manufacturer Name'}), 'product_code': forms.TextInput(attrs={'placeholder': 'Enter Product Code'}), 'brand_name': forms.TextInput(attrs={'placeholder': 'Enter Brand Name'}), 'exemption': forms.TextInput(attrs={'placeholder': 'Enter Exemption'}), … -
I am encountering an Apache error while deploying a Django site
Faced Apache error while deploying Django site with MySQL db. Without Apache, the site works perfectly, but when you enable it, this error is thrown. I can't figure it out for several days. This is what the logs give out: [Wed Jul 21 12:49:59.142758 2021\] \[wsgi:error\] \[pid 24588:tid 140415838369536\] \[remote 95.56.215.234:56573\] mod_wsgi (pid=24588): Target WSGI script '/bigchina/django/bigchina/bigchina/wsgi.py' cannot be loaded as Python module. \[Wed Jul 21 12:49:59.142923 2021\] \[wsgi:error\] \[pid 24588:tid 140415838369536\] \[remote 95.56.215.234:56573\] mod_wsgi (pid=24588): Exception occurred processing WSGI script '/bigchina/django/bigchina/bigchina/wsgi.py'. \[Wed Jul 21 12:49:59.144156 2021\] \[wsgi:error\] \[pid 24588:tid 140415838369536\] \[remote 95.56.215.234:56573\] Traceback (most recent call last): \[Wed Jul 21 12:49:59.144210 2021\] \[wsgi:error\] \[pid 24588:tid 140415838369536\] \[remote 95.56.215.234:56573\] File "/bigchina/django/bigchina/bigchina/wsgi.py", line 18, in <module> \[Wed Jul 21 12:49:59.144217 2021\] \[wsgi:error\] \[pid 24588:tid 140415838369536\] \[remote 95.56.215.234:56573\] application = get_wsgi_application() \[Wed Jul 21 12:49:59.144257 2021\] \[wsgi:error\] \[pid 24588:tid 140415838369536\] \[remote 95.56.215.234:56573\] File "/bigchina/venv/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application \[Wed Jul 21 12:49:59.144263 2021\] \[wsgi:error\] \[pid 24588:tid 140415838369536\] \[remote 95.56.215.234:56573\] django.setup(set_prefix=False) \[Wed Jul 21 12:49:59.144269 2021\] \[wsgi:error\] \[pid 24588:tid 140415838369536\] \[remote 95.56.215.234:56573\] File "/bigchina/venv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup \[Wed Jul 21 12:49:59.144274 2021\] \[wsgi:error\] \[pid 24588:tid 140415838369536\] \[remote 95.56.215.234:56573\] apps.populate(settings.INSTALLED_APPS) \[Wed Jul 21 12:49:59.144280 2021\] \[wsgi:error\] \[pid 24588:tid 140415838369536\] \[remote 95.56.215.234:56573\] File "/bigchina/venv/lib/python3.6/site-packages/django/apps/registry.py", … -
Django not collecting all my static files
This my settings.py code, I have made a folder staticdie and copied all my static files in it. STATIC_URL = '/static/' STATICFLIES_DIRS = [ os.path.join(BASE_DIR, 'staticdie') ] STATIC_ROOT = os.path.join(BASE_DIR, 'assets') When I put python manage.py collectstatic it creates a folder 'assets' and only displays admin files in it. Its not collecting all my static files from staticdie folder. I'm using travello template from colorlib. link(https://www.dropbox.com/sh/gf8x8xjwidq20cz/AABPlOsXmijnz0-yjxYj9ebsa?dl=0) What am I missing? -
How to redirect unauthenticated users to login page?
Im developing a web application using React and Django Sessions with Django Rest Framework for authentication. I have already configured sessions to be given to users on login. I am trying to find a way to redirect unauthenticated users to login page from any page in the web application. I have tried to obtain the value of the sessionid cookie seen here so that I can redirect users if the .length value == 0. if (getCookieValue('sessionid').length === 0) { return <Redirect to="/login" /> } However, since the sessionid cookie is an HTTP cookie, JavaScript is unable to obtain the value. Thus, it is always 0. How can I obtain the value of the HTTP cookie? Or, is there any other way to achieve my desired effect? -
assertEqual getting failed while values are same
I have below test case assert code self.assertEqual( response.data['results'], [ ('id', self.bookmark.id), ('title', self.bookmark.title), ('color', self.bookmark.color), ('user', self.bookmark.user.id), ('project', self.bookmark.project.id), ] ) response.data['result'] is : [OrderedDict([('id', 7), ('title', 'bookmark'), ('color', 'yellow'), ('user', 2), ('project', 1)])] compare list value is : [('id', 7), ('title', 'bookmark'), ('color', 'yellow'), ('user', 2), ('project', 1)] failure msg : AssertionError: [OrderedDict([('id', 7), ('title', 'bookma[52 chars]1)])] != [('id', 7), ('title', 'bookmark'), ('color[37 chars], 1)] can anyone please help? -
How pass multiple attributes to View on Button Click?
I am using Django as my web Framework. On my website there is a view that shows all "projects" of a user. Here the user has the possibility to leave the project or to add a user to the project. When a user presses a button, I want the respective action to be executed. To check if the share or leave button has been pressed i have added a button in my button: <form method="POST"> <button name="leave_project" type="submit" ...>...</button> </form> and can then check in the views: if 'leave_project' in request.POST: However, now I still need the ID of the project that was clicked on. How can I also pass the ID? I know that I could solve the problem by adding a new view with the ID in the url. But then the page would have to be reloaded which I would like to avoid. -
best article/resource for DJANGO + REACT stack
I've been learning Django and React separately for a long time. I want to use them together as a stack now. I know, there are so many articles/tutorials about this already. But everyone has their own method. Can someone plz tell me the BEST way to do so? Any article/video/or previously asked StackOverflow question will do me good. Thanks