Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Database Relationship - Django Models
I am developing an application where it requires database. I am using Django 1.10 to develop this application. The database relationship is as it goes: A project should be able to add documents. Under the same project's documents, user should be able to add multiple testcases under the same document. A project can contain multiple documents and a document can contain multiple testcases. This is what I've written so far in my Models. class Testcase(models.Model): testid = models.IntegerField('Test ID', primary_key=True) title = models.CharField(max_length=255) teststeps = models.TextField('Test Steps') results = models.TextField('Expected Result') def __str__(self): return self.title class Document(models.Model): title = models.CharField(max_length=255) version = models.CharField(max_length=255,unique=False) pub_date = models.DateTimeField('Published Date') testcases = models.ForeignKey(Testcase) def __str__(self): return self.title def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Project(models.Model): title = models.CharField(max_length=255) version = models.CharField(max_length=255,unique=False) release_date = models.DateField() documents = models.ForeignKey(Document) testcases = models.ForeignKey(Testcase) def __str__(self): return self.title And the fields of testcases should be of no limit text. Any help would be greatly appreciated. TIA. -
trying to install webpack on digitalocean server
I'm trying to install webpack on my digitalocean server so i can use ReactJS with my Django Application. However, after setting up package.json, webpack.base.config.js and webpack.local.config.js I keep getting the following error when running node_modules/.bin/webpack --config webpack.local.config.js. The error is /usr/bin/env: ‘node’: No such file or directory When i cd into node_modules and then .bin , I can clearly see the webpack file there ,however, when using WinSCP or Filezilla to go into node_modules I can't see the .bin folder anywhere. I'm following this tutorial https://github.com/mbrochh/django-reactjs-boilerplate/tree/step3_add_django_webpack_loader and I'm stuck on the last step of part 3 . This is how my folder looks root ./django_project ./node_modules ./reactjs ./manage.py .package.json .webpack.local.config.js .webpack.base.config.js Edit: I've also made sure I have npm and nodejs both installed on the machine -
How to using django-import-export to export records sorted by a different column?
I followed documentation in https://django-import-export.readthedocs.io/ to export my Country model using django-import-export package: class Country(models.Model): class Meta: db_table = 'country' verbose_name_plural = 'countries' ordering = ['iso_code'] iso_code = models.CharField( verbose_name='ISO code', help_text='2-character ISO country code', max_length=2, blank=False, ) un_code = models.CharField( verbose_name='UN code', help_text='3-character UN country code', max_length=3, blank=False, ) english_name = models.CharField( verbose_name='English name', help_text='Country name in English', max_length=100, blank=False, ) The resource for country model is: class CountryResource(resources.ModelResource): class Meta: model = Country export_order = ('id', 'iso_code', 'un_code', 'english_name') To export the model, I run: >>> dataset = CountryResource().export() >>> print(dataset.csv) The results (partial): id,iso_code,un_code,english_name 6,AD,AND,Andorra 217,AE,ARE,United Arab Emirates 1,AF,AFG,Afghanistan 8,AI,AIA,Anguilla Note that the results are ordered by the iso_code column which is given in the Country model's Meta class. Without changing the ordering specified in model's Meta class, however, I want to export the records sorted by another column only during the export. For example, I want to the exported records sorted by id. How could I achieve that? Thanks. -
Django not serving static files with even after collectstatic
i'm having problems with django static files in production.I know django requires that you collectstatic during deployment, which i did. The real problem comes when i try to access my page on the browser and i get a 403 forbidden error on all static files. I tried changing my permissions and ownership of var/www/html folders to 755 and files to 644 but still no luck. How do i make my static files load? 403 forbidden errors please advise me on what to do, i have been struggling with this problem for days now. thanks in advance, Dennis -
jQuery .load() on loaded content
I'm not able to get jQuery's load function to work on previously loaded content. The event listener is working on the newly loaded content, because I'm able to get an alert to go off. The relevant code is below. index.js: $(document).ready(function () { $('#create').click(function () { $('#select').load(EDIT_URL); }); $('#select').on("click", '#cancel', function () { // alert("ok"); $('#select').load(SELECT_URL); }); }); The alert goes off just fine when it's not commented out, but nothing happens for the load. I'm using Django with Python 2.7. In index.html: <!DOCTYPE html> <html> <head> {% load staticfiles %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="{% static 'tracker/index.js' %}"></script> <script> var EDIT_URL = "{% url 'edit' %}"; var SELECT_URL = "(% url 'select' %}"; </script> </head> <body> <div id="search">{% include 'tracker/search.html' %}</div> <div id="select">{% include 'tracker/select.html' %}</div> </body> </html> select.html: <!DOCTYPE html> <html> <body> <p>Select a character to edit it, or click create to make a new character.</p> <button id="create" name="edit">Create</button> </body> </html> edit.html: <!DOCTYPE html> <html> <body> {% if character.id %} <h2>Editing {{ character.name }}</h2> <form action="{% url 'edit' character.id %}" method="post"> {% csrf_token %} {% for field in form %} <p>{{ field.label_tag }} {{ field }}</p> {% endfor %} <input type="submit" name="action" value="Delete" /> <input type="submit" name="action" value="Save" /> … -
django: How to use a ListSerializer on a list of different models?
I used the chain function from the itertools module. combined = list(chain(Post.objects.all(), PhotoPost.objects.all())) So I have a list that goes like that: [<Post: Post object>, <PhotoPost: PhotoPost object>] And I want my own combine method to return a serialized list of these mixed models. s = CombinedPostSerializer.combine(combined) I have a class method that takes in the list and tries to append the serialized list. class CombinedPostSerializer: @classmethod def combine(cls, models): combined_dicts = [] for model in models: if model.__class__.__name__ == 'Post': combined_dicts.append(TextMemoSerializer(model)) else: combined_dicts.append(PhotoPost(model)) return ListSerializer(combined_dicts, many=True) I get the error: AssertionError: 'child' is a required argument. -
Django ignores select_related, makes more requests to fetch related objects
I'm making django api for an internship application and run into optimization problem, and while my previous problem was almost fixed, i've run into related problem. The rest of my code and initial problem are here: I'm using select_related as can be seen here in my view: @api_view(["GET"]) def bunnyList(request, vegetableType): """ Displays heap-sorted list of bunnies, in decreasing order. Takes word after list ("/list/xxx") as argument to determine which vegetable list to display""" if vegetableType in vegetablesChoices: vegetables = Vegetable.objects.filter(vegetableType=vegetableType).select_related('bunny') vegetables = list(vegetables) if len(vegetables) == 0: return Response({"No bunnies": "there is 0 bunnies with this vegetable"}, status=status.HTTP_204_NO_CONTENT) heapsort(vegetables) bunnies = [vegetable.bunny for vegetable in vegetables] serialized = BunnySerializerPartial(bunnies, many=True) return Response(serialized.data, status=status.HTTP_200_OK) else: raise serializers.ValidationError("No such vegetable. Available are: " + ", ".join(vegetablesChoices)) This should perform only one query, but as i can see in django debug toolbar is making one + 200 other (one for each vegetable object) in list comprehension, as if it it is completely ignoring the join in the select_related query. The performed queries are: SELECT ••• FROM "zajaczkowskiBoardApi_vegetable" INNER JOIN "zajaczkowskiBoardApi_bunny" ON ("zajaczkowskiBoardApi_vegetable"."bunny_id" = "zajaczkowskiBoardApi_bunny"."id") WHERE "zajaczkowskiBoardApi_vegetable"."vegetableType" = '''carrots''' And this one slighly modified for all objects: SELECT ••• FROM "zajaczkowskiBoardApi_vegetable" WHERE "zajaczkowskiBoardApi_vegetable"."bunny_id" … -
django filter postgres json field variable not defined
I am new to working with Django and postgres JSONFields. The following view reports a name 'snapshot__timestamp' is not defined Model: class Snapshot(models.Model): id = PGUUIDField(primary_key=True) snapshot = JSONField(help_text=("Snapshot of config tree values")) View: def get_queryset(self): if len(self.request.query_params) > 0: try: startdate = time.strptime(self.request.query_params.get('startdate', None),'%Y-%m-%d %H:%M:%S') enddate = time.strptime(self.request.query_params.get('enddate', None), '%Y-%m-%d %H:%M:%S') return Snapshot.objects.filter(Q(snapshot__timestamp>=startdate) & Q(snapshot__timestamp<=enddate)) except Exception as e: print(e) logger.exception(e) return Snapshot.objects.none() return Snapshot.objects.all() Example json field entry: {"tree": {"asdf": "values"}, "pollgroup": [1, 3], "timestamp": "2017-7-2 00:00:00"} All of the examples I have found show the modelfield__json key in the query. What am I doing wrong? -
How to get latest data from database in django
The error i am getting is "'help' object is not iterable". How do i fetch the latest record from the db and get it displayed on my destination html page My views.py is def about_experiment(request,ex_link_name): researcher = None study = None posts = None if request.method == 'POST': form = AboutHelp(request.POST) posts = help.objects.filter().order_by('-date')[0] #print(posts) if form.is_valid(): obj = form.save(commit = False) obj.save() researcher = form.cleaned_data['researcher'] study = form.cleaned_data['study'] else: form = AboutHelp() return render(request, 'about_experiment.html', {'posts': posts}) my destination page about_experiment.html is {% for help in posts %} <h4><b>{{ help.study }}</b></h4> <p>posted by {{ help.researcher }} on {{help.date}}</p> {% endfor %} -
Reducing database access when same query on multiple similar objects
I have an operation in one of my views order_details = [order.get_order_details() for order in orders] Now order.get_order_details() runs one database query. So for current situation. Depending on size of orders the number of database access will be huge. Before having to use cache, is there anything that can speed this up? Is it possible to merge all the select operations into one single database operation? Will making it an atomic transaction using transaction.atomic() increase any performance? because technically the query will be sent at once instead of individually, right? Edit: is there any design changes/ pattern that will avoid this situation? -
Internal Server Error during migration to mysql-django-uwsgi-nginx
I've have been following this tutorial However I decided to migrate to mysql database but all I get is an Internal Server Error text on main page and usually you get from django very accurate explanation why did error occurred (yes DEBUG = True). If I switch back to sqlite in settings.py it works again but I don't think sqlite is for production so I need different db like mysql. Do you know why this error happens or at least where can I find error log? I'm loosing my mind to crack this. I know that problem is with mysql but where! I tried to check did I install what i need: sudo apt-get install libmysqlclient-dev sudo pip3 install mysqlclient sudo apt-get install python-mysqldb but they are already instaled I tried to reset instances: sudo systemctl restart uwsgi sudo systemctl daemon-reload sudo systemctl restart uwsgi sudo nginx -t && sudo systemctl restart nginx I tried to set up different settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql',#or mysql.connector.django 'NAME': 'db', 'USER':'username', 'PASSWORD':'password', 'HOST': 'localhost', # or ip-address where the site is hosted 'PORT': '3306', # or '' } } -
Django REST Framework Forbidden CSRF cookie not set
I have this view from rest_framework import parsers, renderers from rest_framework.authtoken.models import Token from rest_framework.authtoken.serializers import AuthTokenSerializer from rest_framework.response import Response from rest_framework.views import APIView from .serializers import EmailUserSerializer from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt @method_decorator(csrf_exempt, name='post') class ObtainAuthToken(APIView): throttle_classes = () permission_classes = () parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,) renderer_classes = (renderers.JSONRenderer,) serializer_class = AuthTokenSerializer def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) user_serializer = EmailUserSerializer(user) return Response({'token': token.key, 'user': user_serializer.data}) obtain_auth_token = ObtainAuthToken.as_view() and this url urlpatterns = [ url(r'^login/$',views.obtain_auth_token, name='get_auth_token'), url(r'^login2/$',ObtainAuthToken, name='get_auth_token'), ] i'm trying posting with postman like this: 127.0.0.1:8000/api/login2/ but i can only receive this error Forbidden (CSRF cookie not set.): /api/login2/ [02/Jul/2017 22:49:11] "POST /api/login2/ HTTP/1.1" 403 2891 I know there are hundreds of post like this, I searched for a long time a solution but nothing seems working tryied like this urlpatterns = patterns('', url('^login2/$', csrf_exempt(ObtainAuthToken)), ... ) this from django.utils.decorators import method_decorator class LoginView(APIView): @method_decorator(csfr_exempt) def dispatch(self, *args, **kwargs): ... and also this from django.utils.decorators import method_decorator @method_decorator(csrf_exempt, name='dispatch') class LoginView(APIView): ... and this @method_decorator(csrf_exempt, name='post') class ObtainAuthToken(APIView): throttle_classes = () ... @csrf_exempt def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) -
Possible Bug on Django 1.11 with multitable Inheritance or possible bug on python 3.5 or am i?
Using python 3.5.2 and django 1.11 multitable inheritance like this: class Artist(ArtistParent): biography = models.CharField(max_length=255, blank=True, null=True) avatar = models.ImageField(null=True, blank=True, upload_to=settings.IMAGES_FOLDER) owner = models.ForeignKey("accounts.User", related_name="my_artists", null=True, blank=True, on_delete=deletion.SET_NULL) class SimilarBand(ArtistParent): pass Every work out just fine, but using the ORM interface: >>> ArtistParent.objects.all().delete() (0, {}) >>> SimilarBand.objects.all().delete() (0, {}) >>> ArtistParent.objects.all().delete() (0, {}) >>> SimilarBand.objects.all().delete() (0, {}) >>> SimilarBand.objects.create(name="Similar Band Test") <SimilarBand: Similar Band Test> >>> SimilarBand.objects.all() <QuerySet [<SimilarBand: Similar Band Test>]> >>> ArtistParent.objects.all() <QuerySet [<ArtistParent: Similar Band Test>]> >>> SimilarBand.objects.all().count() 1 >>> ArtistParent.objects.all().count() 1 >>> len(ArtistParent.objects.all()) 1 >>> len(SimilarBand.objects.all()) 1 >>> [print(o) for o in ArtistParent.objects.all()] Similar Band Test [None] >>> [print(o) for o in SimilarBand.objects.all()] Similar Band Test [None] >>> [print(o) for o in ArtistParent.objects.filter(similarband__isnull=False)] Similar Band Test [None] >>> My bug is about that second None that iterating over the queryset brings, is that normal? or is a bug on the Manager? However, it works right if i use a for construct like this: >>> [print(i) for i in list(SimilarBand.objects.all())] Similar Band Test [None] >>> for i in list(SimilarBand.objects.all()): ... print(i) ... Similar Band Test Either way, i'm using a serpy Serializer, and give an error, when i pass the queryset. Thanks for the Help -
Django. Make a many-page showcase
StackOverflow, I want to make a many-page showcase. On the first page, it`ll be first 25 items, in the second - from 26 to 50 and so on. But how can I do this? here is urls.py: products = Product.objects.order_by('-date') urlpatterns = [ url(r' regexp ', ListView.as_view(queryset=products, template_name='shop/shop.html')),] It must to asnwer the requests like this: mysite.com/shop/2 and also display products[25*(request_number-1) : 25*request_number] items on page Thanks in advance! -
DRF serializer update nested user
i'm using Django 1.11 and the Django Rest Framework in order to create an API, where a user can create and update an employee which is related to the django user model. The stripped down code i've got looks like this: I've got this model: class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='employee') uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) these two viewsets: class UserViewSet(viewsets.ModelViewSet): serializer_class = serializers.UserSerializer permission_classes = [permissions.IsAuthenticated] and class EmployeeViewSet(viewsets.ModelViewSet): serializer_class = serializers.EmployeeSerializer permission_classes = [permissions.IsAuthenticated] and these two serializers: class UserSerializer(serializers.HyperlinkedModelSerializer) class Meta models = User fields = ('url', 'id', 'username', 'email', 'is_staff', 'first_name', 'last_name', 'password) read_only_field = ('id',) def validate(self, data) # ... Check if data is valid and if so... return data and class EmplyoeeSerializer(serializers.HyperlinkedModelSerializer): user = UserSerializer() class Meta: field = ('url', 'uuid', 'user') read_only_field = ('uuid') def validate(self, data): return data def create(self, validated_data): user = User(**validated_data['user']) user.save() employee = Employee(user=user) employee.save() return employee def update(self, employee, user): employee.user.username = user.username employee.user.email = user.email employee.user.first_name = user.first_name employee.user.last_name = user.last_name employee.user.is_staff = user.is_staff # ... Check if password has changed, and if so... employee.user.set_password(user.password) employee.user.save() employee.save() return employee also i've got these two routers in my urls.py router = routers.DefaultRouter() router.register(r'api/user', views.UserViewSet, base_name='user') router.register(r'api/employee', … -
Can't figure out why form.has_changed() is always true?
I'm trying to learn Django and have come up with a situation I can't figure out. I have the following code: def contact_add(request): if request.method == 'POST': form = ContactManageForm(request.POST) if form.is_valid(): if form.has_changed(): # <-- ALWAYS RETURNS TRUE! form.clean() ... elif 'id' in request.GET: # Request to show an existing contact new_contact_dynamic = contacts.models.PersonDynamic.objects.get(person_static = request.GET['id'], current_record_fg = True) form = ContactManageForm(new_contact_dynamic.__dict__, initial=new_contact_dynamic.__dict__) else: # This must be to add a new contact form = ContactAddForm() return render(request, 'contact_manage.html', {'form': form}) So, if I'm sent an ID number, I read a record and display it on the screen. My template gives the user a 'submit changes' button. My problem, as noted above, is that Django always shows that the form has changed, even if the user hasn't changed any data on the screen (i.e. he just hit the submit changes button without changing anything). So, am I doing something obviously wrong in my code that's creating this situation? Am I misinterpreting how the form.has_changed() method works? It's my assumption that when I use the initial=parameter after a GET request, Django is storing that data somewhere and knows the context when the user then hits the 'submit data' button, is … -
unable to use continuous delivery on AWS for a django app(nginx, psql)
I have tried multiple tutorials in order to run my application which is running simply good with docker, django, nginx, postgres. I have my docker-compose.yml file ready, should not it be simple to ship it to the cloud ? I tried Elasticbeanstalk, getting multiple errors that are hard to debug. AWS does not seem to support docker-compose.yml and I should use their Dockerrun.aws.json, I tried also ECS, but it seems also to be not easy. Does any one know a complete, thorough tutorial on that? By the way, I am using codeship, and all tests runs well, but deployment is also failing all the time. -
TypeError: int() argument must be a string, a bytes-like object or a number, not 'WSGIRequest'
need to create middleware that stores all requests and execution time in Django. I created a column in db models.py class RequestInformation(models.Model): list_of_requests = models.CharField(max_length=200) And also looked through django docs and created middleware.py from profileapp.models import RequestInformation class CustomRequestMiddleware(object): def process_request(self, request): http_information = RequestInformation(request) http_information.save() Also added custom middleware in settings. But don't know what to do next. TypeError: int() argument must be a string, a bytes-like object or a number, not 'WSGIRequest' Sorry fo stupid question, didn't find ho to solve this.Thanks in advance -
How to order a list of locations based on their latitude and longitude?
I am developing a Python/Django website with thousands of touristic destinations. I have clustered these locations by city with DBSCAN and identified the center of each cluster (lat/lng). I would now like to present these clusters in a logical order, i.e. like they would be presented in a guidebook based on their geographical location in the country : Eg: New York Washington Miami Dallas San Diego San Franciso If I sort them by latitude, for example, i get: New York Washington San Francisco San Diego Dallas Miami ...which is completely scattered over the country. Any good idea to sort them in a more logical order? -
local variable referenced before assignment django error
This is my view.py and when i have a form which when i submit with the required fields it gives an appropriate output but when i don't input anything in the form and click submit i get an error saying "local variable 'researcher' referenced before assignment". Also i want to know how do i keep my form data saved on the destination page def about_experiment(request,ex_link_name): if request.method == 'POST': form = AboutHelp(request.POST) if form.is_valid(): researcher = form.cleaned_data['researcher'] study = form.cleaned_data['study'] else: form = AboutHelp() return render(request, 'about_experiment.html', {'researcher': researcher, 'study': study}) my form on the source page is <form action="{% url 'lazer.views.about_experiment' exp.link_name %}" method="POST" name="form"> {% csrf_token %} <label>Researcher Name(s):<input type="text" name="researcher"> <lable>Study Summary<textarea rows="10" cols="50" placeholder="here you go" maxlength="500" class="form-control" name="study"></textarea> <br> <input type = "submit" value="Submit" class="btn btn-primary" /> </form> My destination page where the form outputs are present <h4> Name : {{ researcher }} </h4><br> <h4> Summary : {{ study }} </h4> -
how to deploy a django website on cpanel
I build a web application using django and python but I don't know to how to deploy it on a server. Please someone guide me how to deploy a Django and python based website on a cpanel? -
how to fix TypeError: expected string or bytes-like object?
when i submit, this error is blow up, who can help, welcome, bro)! stack ask me add more text, but what to add? if everything was told? but what to add? if everything was told? The error is related to the date fulltraceback > Internal Server Error: /accounts/reset_activation_key/ Traceback (most > recent call last): File > "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\lib\site-packages\django\core\handlers\exception.py", > line 41, in inner > response = get_response(request) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\lib\site-packages\django\core\handlers\base.py", > line 187, in _get_response > response = self.process_exception_by_middleware(e, request) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\lib\site-packages\django\core\handlers\base.py", > line 185, in _get_response > response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\newstudio\accounts\views.py", > line 140, in reset_activation_key > profile.save() File "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\lib\site-packages\django\db\models\base.py", > line 806, in save > force_update=force_update, update_fields=update_fields) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\lib\site-packages\django\db\models\base.py", > line 836, in save_base > updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File > "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\lib\site-packages\django\db\models\base.py", > line 903, in _save_table > forced_update) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\lib\site-packages\django\db\models\base.py", > line 953, in _do_update > return filtered._update(values) > 0 File "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\lib\site-packages\django\db\models\query.py", > line 664, in _update > return query.get_compiler(self.db).execute_sql(CURSOR) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\lib\site-packages\django\db\models\sql\compiler.py", > line 1191, in execute_sql > cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) File > "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\lib\site-packages\django\db\models\sql\compiler.py", > line 863, in execute_sql > sql, params = self.as_sql() File "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\lib\site-packages\django\db\models\sql\compiler.py", > line 1157, in as_sql > val = field.get_db_prep_save(val, connection=self.connection) File > "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\lib\site-packages\django\db\models\fields\__init__.py", > line … -
Using ReactsJS to filter data received from an API
I'm trying to build a news/article website for education purposes using Django and ReactJS. Currently, I've created an article model in Django and set up an API for ReactJS to talk to. Every article has a headline, image, content, featured and qucikreads properties. featured and quickreads are boolean values. I've successfully set up my ReactJS component to fetch all the articles however, I'm having trouble filtering the articles that have article.featured = true and article.quickreads = true . Currently my component has three states: articles, featured and quickreads. This is how it currently looks class Api extends React.Component{ constructor(){ super(); this.state = { articles: null, featured: null, quickreads: null } } componentDidMount(){ fetch("http://127.0.0.1:8000/articles/articlesapi/").then(request => request.json()).then(response => this.setState({articles: response})) var featured = this.state.articles.filter(article => article.featured === true) var quickreads = this.state.articles.filter(article => article.quickreads === true) this.setState({featured: featured, quickreads: quickreads}) } render(){ return ( <p>Hello World</p> ) } } Although the component gets all the articles it fails to updated featured and quickreads. I get the following error Uncaught TypeError: Cannot read property 'articles' of undefined at componentDidMount (eval at <anonymous>)... Any help as to why this is happening -
how to fix “TypeError: string indices must be integers” when using cleaned_data?
full traceback response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\newstudio\accounts\views.py", line 129, in reset_activation_key email = form.cleaned_data['email'] TypeError: string indices must be integers this is view, where error blows up form = ResetActivatioKey(request.POST or None) if form.is_valid(): email = form.cleaned_data['email'] user = User.objects.get(email=email) profile = UserProfile.objects.get(user=user) if profile.is_active: return redirect('/accounts/login') if profile is not None and not profile.is_active == False : username = user.username email_path = "{0}/ResendEmail.txt".format(settings.EMAIL_FILE_PATH) get_secret_key = activation_key_generator(username) profile.activation_key = get_secret_key profile.key_expires = (timezone.now() + datetime.timedelta(days=2)), profile.save() -
How to add Angular project to Django and Docker
I would like to add Angular 4 project to Docker with Django project? My structure of files look in this way: DockerContainer: Backend Dockerfile Frontend docker-compose.yml requirements.txt I would like to create Angular 4 project in Frontend directory. I can do this using ng new my-app but what should I do next? This is my docker-compose.yml: version: '3' services: db: image: postgres django: build: . command: python3 Backend/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db Dockerfile: FROM python:3.6.1 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/