Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to make "set or get cookies" in Django from js code so that when you switch to another page, the radio does not stop?
` MRP.insert({ 'url': 'http://s7.voscast.com:10196/armnews', 'lang': 'hy', 'codec': 'mp3', 'volume': 65, 'autoplay': true, 'forceHTML5': true, 'jsevents': true, 'buffering': 0, 'title': 'ArmNews 106.9', 'welcome': 'Բարլուս ազիզ', 'wmode': 'transparent', 'skin': 'faredirfare', 'width': 270, 'height': 52 );` -
name 'self' is not defined when running "Tutorial.objects.all()" in cmd
I am trying to do the webapp project using django here's the code in the model.py from django.db import models class Tutorial(models.Model): tutorial_title = models.CharField(max_length=200) tutorial_content = models.TextField() tutorial_published = models.DateTimeField('date published') def __str__(self): return self.tutorial_title When running Tutorial.objects.all() in the cmd, it return errors "name self is not defined" -
django channels cannot authenticate user using django inbuilt authentication system as mentioned in documents
I want to run a consumer which requires authenticated user in my channels application channels disconnecting the consumer saying that user isn't authenticated but the user is authenticated and his cookies are updated in the browser I have followed channels documentation which authenticates user class LikeConsumer(AsyncJsonWebsocketConsumer): async def connect(self): self.user = self.scope["user"] # user = self.scope['user'] user=self.user print(user) if user.is_anonymous: await self.close() print("user is anonymous") else: await self.accept() # user_group = await self._get_user_group(self.scope['user']) await self.channel_layer.group_add("{}".format(user.id), self.channel_name) print(f"Add {self.channel_name} channel to post's group") print('connected') # @database_sync_to_async # def _get_user_group(self, user): # if not user.is_authenticated: # raise Exception('User is not authenticated.') # else: # print("user is not authenticated") # return user async def disconnect(self,close_code): user = self.scope['user'] await self.channel_layer.group_discard("{}".format(user.id), self.channel_name) print(f"Remove {self.channel_name} channel from post's group") i'm not sure what exactly the mistake is user is anonymous WebSocket DISCONNECT /like/ [127.0.0.1:50710] -
Plot audio from microphone in Django
I want to record 5 seconds of audio periodically and then send it as a blob via ajax to the server, and finally plot the audio waveform. I'm using the function below to record and send the audio to the server: function start_microphone(){ var options = {mimeType: 'audio/webm'}; const recorder = new MediaRecorder(audioStream, options); const chunks = []; recorder.ondataavailable = function(e) { chunks.push(e.data); } recorder.onstop = function(e) { var data = new FormData(); data.append('file', new Blob(chunks)); $.ajax({ url : 'ajax/analyze_audio/', type: 'POST', data: data, contentType: false, processData: false, success: function(data) { console.log("boa!"); }, error: function() { console.log("not so boa!"); } }); setTimeout(start_microphone, 0); } setTimeout(()=> recorder.stop(), 5000); // we'll have a 5s media file recorder.start(); } Then, with python, I try to read it and plot it: def analyze_audio(request): audio = request.FILES['file'] readaudio = audio.read() path = default_storage.save('somename.webm', ContentFile(readaudio)) data = np.fromfile(path, dtype=np.int16) os.remove(path) save(data, "foo.png") return JsonResponse({}) def save(data, name): if os.path.exists(name): os.remove(name) fig = plt.figure(frameon=False, figsize=(100, 128), dpi=1) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() ax.margins(0) fig.add_axes(ax) ax.plot(data, "k") fig.canvas.draw() plt.savefig(name) I do save the audio to a file "somename.webm" just to check by myself that the audio is well received and it does sound as it … -
Dynamically create model from form builder in django
I have to create model from form builder. Form field as column and title as model. is possible to implement this concept in Django? Create dynamically model from selected field of form builder and that model register in admin. i.g. I have a saree as product and that contain attribute color, prize, size and then add mobile as another product that contain attribute color, prize, ram, screen_size etc. here, color and prize common field and remaining attribute different so, create two different model in django -
How to display post and related comments on single page?
I am unable to design a code to render one particular post and it's related comments. The issue is maybe in views.py or the url. I have looked at multiple sources without any results. I am a novice to coding and feel like I am missing some essential point. Posts and comments are getting created correctly and all comments get the correct post_id assigned. My models.py is set up like this: class Post(models.Model): title = models.CharField(max_length=1000) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog-home') class Comment(models.Model): cid = models.AutoField(primary_key=True) author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) comment = models.TextField() comment_date = models.DateTimeField(default=timezone.now) def save(self, *args, **kwargs): super(Comment, self).save(*args, **kwargs) def __str__(self): return self.comment def get_absolute_url(self): return reverse('blog-home') class PostComment(models.Model): posts = models.ForeignKey(Post, on_delete=models.CASCADE) comments = models.ForeignKey(Comment, on_delete=models.CASCADE) My views.py is set up like this: class PostCommentView(DetailView): model = PostComment template_name = 'blog/post_detail.html' context_object_name = 'comments' ordering = ['-comment_date'] paginate_by = 7 def get_queryset(self): commentor = get_object_or_404(Comment, post_id=self.kwargs.get('post_id')) return Post.objects.filter(post_id=commentor).order_by('-comment_date') and the template for the detail view is as below: {% extends "blog/base.html" %} {% block content%} <article class="media content-section"> <img class="rounded-circle article-img" src="{{object.author.profile.image.url}}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" … -
take approved replies in comments
i took approved/published comments. However, all approved or unconfirmed replies appear. i tried this method first comment_replies=Comment.replies.objects.filter(post=post,reply=None,statusc=2).order_by('-date') However it doesn't work (sorry my misspellings) i think this problem is in this code= {% for reply in comment.replies.all %} views.py def post_detail(request,slug): post=get_object_or_404(Post,slug=slug) comments=Comment.objects.filter(post=post,reply=None,statusc=2).order_by('-date') comment_count=len(Comment.objects.filter(post=post, statusc=2)) if request.method=='POST': comment_form = CommentForm(request.POST or None) if comment_form.is_valid(): name=request.POST.get('name') email=request.POST.get('email') comment=request.POST.get('comment') reply_id=request.POST.get('id_comment') comment_qs=None if reply_id: comment_qs=Comment.objects.get(id=reply_id) comment=Comment.objects.create(post=post,name=name,email=email,comment=comment,reply=comment_qs,statusc=1) comment.save() messages.success(request, "Yorumunuz Onaylandıktan sonra yayınlanacaktır") return HttpResponseRedirect(post.get_absolute_url()) else: comment_form=CommentForm() context={ 'post':post, 'comments':comments, 'comment_form':comment_form, 'comment_count':comment_count, } return render(request,'post/post.html',context) models.py class Comment(models.Model): STATUS_C_DRAFT = 1 STATUS_C_PUBLISHED = 2 STATUSES_C = ( (STATUS_C_DRAFT, 'Draft'), (STATUS_C_PUBLISHED, 'Published'), ) post=models.ForeignKey(Post,verbose_name='post',related_name='comment',on_delete=models.CASCADE) name=models.CharField(verbose_name="name",max_length=60,blank=False) email=models.EmailField(max_length=120,blank=False,verbose_name="email") comment=models.TextField(max_length=1000,verbose_name="comment") reply=models.ForeignKey('Comment',null=True,related_name='replies',on_delete=models.CASCADE) date=models.DateTimeField(auto_now_add=True) statusc = models.SmallIntegerField(choices=STATUSES_C,default=STATUS_C_DRAFT) class Meta: verbose_name="Yorum" verbose_name_plural="Yorumlar" def __str__(self): return 'Üst Yorum: %s' % (self.comment) html file comments; {% for comment in comments %} <!-- POST COMMENT --> <div class="post-comment"> <!-- POST COMMENT USERNAME --> <p class="post-comment-username">{{ comment.name }}</p> <!-- /POST COMMENT USERNAME --> <!-- POST COMMENT TIMESTAMP --> <p class="post-comment-timestamp">{{ comment.date |timesince }} Önce</p> <!-- /POST COMMENT TIMESTAMP -->... html file comments reply {% for reply in comment.replies.all %} <div class="post-comment"> <!-- POST COMMENT USERNAME --> <p class="post-comment-username">{{ reply.name }}</p> <!-- /POST COMMENT USERNAME --> <!-- POST COMMENT TIMESTAMP --> <p class="post-comment-timestamp">{{ reply.date|timesince }} Önce</p> … -
How to connect microsoft azure dataware house server with django?
Trying to connect to a datawarehouse. This is the configuration I am using DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'dbname', 'USER': 'username', 'PASSWORD': 'pass', 'HOST': 'xyz.database.windows.net', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, }, } When I am trying to run the migrate command its giving me the error that Enforced unique constraints are not supported in Azure Data Warehouse. To create an unenforced unique constraint you must include the NOT ENFORCED syntax as part of your syntax. -
Django Rest Framework: Can't get over strange error
Trying a simple request: urls.py from django.conf.urls import url from django.urls import include, path from rest_framework import routers from django.http import HttpResponse from rest_framework.urlpatterns import format_suffix_patterns from .public_views import NavigationBar router = routers.DefaultRouter() router.register(r'navbar', NavigationBar, basename="NavigationBar") urlpatterns = [ path('', include(router.urls)) ] urlpatterns = format_suffix_patterns(urlpatterns) public_views.py from django.shortcuts import render from rest_framework.views import APIView from rest_framework.permissions import AllowAny from rest_framework.throttling import UserRateThrottle from rest_framework.decorators import api_view, throttle_classes from . view_utils import * class OncePerDayUserThrottle(UserRateThrottle): rate = '1/day' class NavigationBar(APIView): """ obtain up to date navigation bar (or side menu navigation) hierarchy. """ permission_classes = ([AllowAny]) def get(self, request, format=None): """ get user addresses """ return Response("this is a good response") def get_extra_actions(cls): return [] When I API call the /v1/navbar or /v1/navbar/ endpoints (I do have my main urls.py lead all /v1/ traffic to another dedicated urls.py), I am getting the following error: AttributeError at /v1/navbar type object 'NavigationBar' has no attribute 'get_extra_actions' Request Method: GET Request URL: http://web/v1/navbar Django Version: 2.1 Exception Type: AttributeError Exception Value: type object 'NavigationBar' has no attribute 'get_extra_actions' Exception Location: /usr/local/lib/python3.6/site-packages/rest_framework/routers.py in get_routes, line 200 Python Executable: /usr/local/bin/uwsgi Python Version: 3.6.8 Python Path: ['.', '', '/usr/local/lib/python36.zip', '/usr/local/lib/python3.6', '/usr/local/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/site-packages'] Server time: Tue, 2 Jul … -
How to write a data migration to rename objects in the production database?
I changed the instances of "Discipline Points" to "Accountability Points" in the code but I am unable to rename these objects in the database. In a few spots, I have code that grabs a template named "Accountability Points" but this will fail to find an object matching that query because the name of these objects are not changed in the database. An example of code that grabs this is template = NotificationTemplate.objects.get(name="Accountability Points"). Currently, I'm attempting to write a data migration to rename these objects but I'm kind of unsure exactly how to accomplish this. I haven't found much on how to do this specifically, but I've looked at the RenameField migrations operation and I think the solution to my problem could be something similar. I have also tried grabbing all of the objects with the name "Discipline Points" and think a For loop would work to grab each object and rename it. # Generated by Django 1.11.6 on 2019-05-09 21:05 from __future__ import unicode_literals from django.db import migrations def change_to_accountability(apps, schema_editor): notification = apps.get_model('hr', 'NotificationTemplate') discipline = notification.objects.get(name="Discipline Points") for disc in discipline: disc.new_name = "Accountability Points" disc.save() class Migration(migrations.Migration): dependencies = [ ('hr', '0012_auto_20190509_1705'), ] operations = [ … -
Snippets aren't displayed in the wagtail admin page
I have a snippet called event, After upgrading to wagtail 2.5.1 (Still i am not sure if this issue is related to version 2.5.1) The previous events aren't displayed on the wagtail admin page anymore. However i am able to search for them in the search box.any help is appreciated -
How to change Text field to Buttons
Can any body tell me the best practice or way to change Text field to the Button with value 0 or 1. Let me clear what I want so i have here(see below) django form with the 2 field called Up_vote and Down_vote and when I submit it stores pretty nicely into the Votes table. But what I what is to have two buttons like stacoverflow have for up_vote and down_vote and when someone press on the up_vote it should submit value 1 automatically to the database and when someone press the down_Vote it sould submit the value 0 to the database table. see like this: so basically how i can convert text fields to the two buttons, I dont now how i can do with the javascript or with other method. -
Problems using wildwebmidi midi player
I'm trying to add this github code to my project: https://github.com/yazgoo/wild-web-midi It works perfectly when I try it local, but when I try it in my webpage, based on Django, it throws me the following error: uncaught exception: could not load memory initializer wildwebmidi.js.mem I try to load all the scripts from my static folder. Does anybody know how to manage this problem? I'm not sure if it is because of the URLs or something like that. -
How to export django model to pandas dataframe sorted by specific column
I'm working on a django web app which visualizes data stored in a SQLite in the browser using bokeh. Since I want to display the data as a stacked area plot I concluded it might be helpful to use the pandas library to save the data from my django model to a dataframe before plotting. My Django models.py includes the following model: class Activity(models.Model): def __str__(self): return self.title title = models.CharField(max_length=50) sport = models.ForeignKey(Sport, on_delete=models.CASCADE) date = models.DateField(blank=False) duration = models.FloatField() distance = models.FloatField(blank=True, null=True) description = models.CharField(max_length=50, blank=True, null=True) trace_file = models.ForeignKey(TraceFiles, on_delete=models.CASCADE, blank=True, null=True) Some example data in the SQLite db could look similar to: | id | title | date | duration | sport_id | trace_file_id | description | distance | |--------------------------------------------------------------------------------------------| | 1 | biking01 | 2019-01-01 | 183 | 1 | 16 | NULL | 142 | | 2 | running17 | 2019-01-01 | 45 | 2 | 2 | NULL | 14 | | 3 | biking02 | 2019-01-01 | 67 | 1 | 18 | NULL | 45 | What would be the best way to read from the model and convert the data to a pandas dataframe? For example I have similar … -
Import error while trying to import a variable within a function in another python script
I have created a function in views.py which is def func(request).Basically, I tried using the variable var, in another python file, say z.py, by typing: from views import func but I got the error ImportError: cannot import name func. Please help me out. I want to use the variable var in the other python script, but am getting this error. -
Auto-Scheduling Django Celery Tasks
I have a django project that checks and backs up a large amount of data from user's accounts they've authorized. Is there a smart way to distribute the scheduling, say if I want to do it twice a day as to not overload my celery server? -
How to automatically start download after user clicks download button which triggers bucket event?
I am making a website on django which allows a user to upload a csv file and convert it to json. Whenever a user uploads a csv document a lambda fuction is triggered the moment the file lands on an s3 bucket where it gets converted to json and saved to another bucket. After the function generates a pre-signed url with the following code: uri_duration = 90 s3Client = boto3.client('s3') url = s3Client.generate_presigned_url('get_object', Params = {'Bucket': bucket, 'Key': filekey'}, ExpiresIn = uri_duration) My question is how could I start the download with the aid of the boto3 library automatically now that the pre-signed url is generated`? I appreciate any help you can provide -
Django Import Error. Cannot import name reciever
I'm learning django and while trying to use Signal and receiver, I receive an ImportError. File "/Library/Python/2.7/site-packages/django/dispatch/__init__.py", line 9, in <module> from django.dispatch.dispatcher import Signal, receiver ImportError: cannot import name receiver I've seen this post and I tried deleting and re-adding the django module(s) but nothing happened. What can I do to fix this and make it work? I'm using django-2.3 and python 3.7.3 -
Django GenericRelation for the update_or_create
I have an issue with using GenericRelation with update_or_create. I have the following models: class LockCode(TimeStampedModel): context_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) context_id = models.PositiveIntegerField() context = GenericForeignKey('context_type', 'context_id') class Mission(DirtyFieldsMixin, models.Model): lock_codes = GenericRelation( LockCode, content_type_field='context_type', object_id_field='context_id', related_query_name='mission' ) I try to create or update LockCode using the mission as a key: mission = .... LockCode.objects.update_or_create( context=mission, defaults={ #some other columns there } And I have the FieldError: Field 'context' does not generate an automatic reverse relation and therefore cannot be used for reverse querying. If it is a GenericForeignKey, consider adding a GenericRelation. It works when I use the context_id and context_type explicitly: LockCode.objects.update_or_create( context_id=mission.pk, context_type=ContentType.objects.get_for_model(Mission), defaults={ #some other columns there } Is it something wrong in my configuration? Or it is only single way to use GenericForeignKey for the update_or_create? -
How to run migrate script?
Trying to run python manage.py migrate but getting error as ('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Enforced unique constraints are not supported in Azure SQL Data Warehouse. To create an unenforced unique constraint you must include the NOT ENFORCED syntax as part of your statement. (104467) (SQLExecDirectW)') -
Django - sqlite3.OperationalError unable to open database file [on hold]
I am developing a small app with the django framework and when trying to serve it via apache2 I get the following error: (sqlite3.OperationalError) unable to open database file (Background on this error at: http://sqlalche.me/e/e3q8) My settings.py entry for the database looks like that: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3') } } the db file exists and has the following rights given by chmod: root@myVPS:/var/www/lab# ls -l db.sqlite3 total 30236 -rwxrwxr-x 1 www-data www-data 3018568 Jul 1 22:14 db.sqlite3 the root folder /var/www/lab: drwxrwxr-x 8 www-data www-data 4096 Jul 2 01:15 lab I read that it might be a problem with the rights but I can't seem to find what I did wrong. Traceback: File "/var/www/lab/venv/lib/python3.5/site-packages/sqlalchemy/engine/base.py" in _wrap_pool_connect 2228. return fn() File "/var/www/lab/venv/lib/python3.5/site-packages/sqlalchemy/pool.py" in connect 434. return _ConnectionFairy._checkout(self) File "/var/www/lab/venv/lib/python3.5/site-packages/sqlalchemy/pool.py" in _checkout 831. fairy = _ConnectionRecord.checkout(pool) File "/var/www/lab/venv/lib/python3.5/site-packages/sqlalchemy/pool.py" in checkout 563. rec = pool._do_get() File "/var/www/lab/venv/lib/python3.5/site-packages/sqlalchemy/pool.py" in _do_get 1355. return self._create_connection() File "/var/www/lab/venv/lib/python3.5/site-packages/sqlalchemy/pool.py" in _create_connection 379. return _ConnectionRecord(self) File "/var/www/lab/venv/lib/python3.5/site-packages/sqlalchemy/pool.py" in __init__ 508. self.__connect(first_connect_check=True) File "/var/www/lab/venv/lib/python3.5/site-packages/sqlalchemy/pool.py" in __connect 710. connection = pool._invoke_creator(self) File "/var/www/lab/venv/lib/python3.5/site-packages/sqlalchemy/engine/strategies.py" in connect 114. return dialect.connect(*cargs, **cparams) File "/var/www/lab/venv/lib/python3.5/site-packages/sqlalchemy/engine/default.py" in connect 437. return self.dbapi.connect(*cargs, **cparams) The above exception (unable to open database file) … -
Django: Pre-populate form with request data
I am trying to pre-populate a Django form based on a users POST request data. Am using FormView, so i overide get_initial but request.POST is always empty. I guess am missing something below is snippet from my view def get_initial(self): initial = super(Yo_EnView, self).get_initial() if self.request.POST: initial.update({'src': self.request.src}) return initial -
Django deployment to AWS using wrong python version?
I'm getting this error when deploying a Django 1.11.5, Python 2.7 application to AWS elasticbeanstalk. [2019-07-02T14:39:08.658Z] INFO [2951] - [Application deployment app-1376-190702_143948@1/StartupStage0/AppDeployPreHook/03deploy.py] : Starting activity... [2019-07-02T14:39:32.424Z] INFO [2951] - [Application deployment app-1376-190702_143948@1/StartupStage0/AppDeployPreHook/03deploy.py] : Activity execution failed, because: Collecting git+git://github.com/django-crispy-forms/django-crispy-forms.git@c243b01a41ff2cab28fba219f39f996c1125195d (from -r /opt/python/ondeck/app/requirements.txt (line 19)) Cloning git://github.com/django-crispy-forms/django-crispy-forms.git (to c243b01a41ff2cab28fba219f39f996c1125195d) to /tmp/pip-IgLSZW-build Could not find a tag or branch 'c243b01a41ff2cab28fba219f39f996c1125195d', assuming commit. Collecting app-version==0.2.1 (from -r /opt/python/ondeck/app/requirements.txt (line 1)) Downloading https://files.pythonhosted.org/packages/ac/a7/dedf1c4302ffcd271cdc788308bd0c4ae0c1b6e8aeef63295259213cfa3b/app_version-0.2.1.tar.gz Collecting appdirs==1.4.3 (from -r /opt/python/ondeck/app/requirements.txt (line 2)) Downloading https://files.pythonhosted.org/packages/56/eb/810e700ed1349edde4cbdc1b2a21e28cdf115f9faf263f6bbf8447c1abf3/appdirs-1.4.3-py2.py3-none-any.whl Collecting awsebcli==3.14.1 (from -r /opt/python/ondeck/app/requirements.txt (line 3)) Downloading https://files.pythonhosted.org/packages/9c/63/e05679b01575a4a25f482ea1f0420bf491853c60c71656eb8badd1040e51/awsebcli-3.14.1.tar.gz (233kB) Collecting backports.ssl-match-hostname==3.5.0.1 (from -r /opt/python/ondeck/app/requirements.txt (line 4)) Downloading https://files.pythonhosted.org/packages/76/21/2dc61178a2038a5cb35d14b61467c6ac632791ed05131dda72c20e7b9e23/backports.ssl_match_hostname-3.5.0.1.tar.gz Collecting bleach==2.1.3 (from -r /opt/python/ondeck/app/requirements.txt (line 5)) Downloading https://files.pythonhosted.org/packages/30/b6/a8cffbb9ab4b62b557c22703163735210e9cd857d533740c64e1467d228e/bleach-2.1.3-py2.py3-none-any.whl Collecting blessed==1.14.2 (from -r /opt/python/ondeck/app/requirements.txt (line 6)) Downloading https://files.pythonhosted.org/packages/07/f5/a0e4b579053c7c01186e1a32b25bfad54fa25468e0e489c44572d39d3bf8/blessed-1.14.2-py2.py3-none-any.whl (64kB) Collecting botocore==1.7.7 (from -r /opt/python/ondeck/app/requirements.txt (line 7)) Downloading https://files.pythonhosted.org/packages/5c/64/b351ade40f18a8c05f1dfd231790bfad81cf97196a4ebedc6eee298945d4/botocore-1.7.7-py2.py3-none-any.whl (3.6MB) Collecting cement==2.8.2 (from -r /opt/python/ondeck/app/requirements.txt (line 8)) Downloading https://files.pythonhosted.org/packages/70/60/608f0b8975f4ee7deaaaa7052210d095e0b96e7cd3becdeede9bd13674a1/cement-2.8.2.tar.gz (165kB) Collecting chardet==3.0.4 (from -r /opt/python/ondeck/app/requirements.txt (line 9)) Downloading https://files.pythonhosted.org/packages/bc/a9/01ffebfb562e4274b6487b4bb1ddec7ca55ec7510b22e4c51f14098443b8/chardet-3.0.4-py2.py3-none-any.whl (133kB) Collecting colorama==0.3.9 (from -r /opt/python/ondeck/app/requirements.txt (line 10)) Downloading https://files.pythonhosted.org/packages/db/c8/7dcf9dbcb22429512708fe3a547f8b6101c0d02137acbd892505aee57adf/colorama-0.3.9-py2.py3-none-any.whl Collecting django==1.11.5 (from -r /opt/python/ondeck/app/requirements.txt (line 11)) Downloading https://files.pythonhosted.org/packages/18/2d/b477232dd619d81766064cd07ba5b35e956ff8a8c5c5d41754e0392b96e3/Django-1.11.5-py2.py3-none-any.whl (6.9MB) Collecting django-adaptors==0.2.5 (from -r /opt/python/ondeck/app/requirements.txt (line 12)) Downloading https://files.pythonhosted.org/packages/a6/fe/320a75cbebdca3217765f89ca18d322c3eeec5e994c9ede4fd5d75e0e1c5/django-adaptors-0.2.5.tar.gz Collecting django-appconf==1.0.2 (from -r /opt/python/ondeck/app/requirements.txt (line 13)) Downloading https://files.pythonhosted.org/packages/5b/78/726cdf3e04660560cf25f9def95b8f2736310c581dabed9adfe60154a9f8/django_appconf-1.0.2-py2.py3-none-any.whl Collecting django-axes==2.3.3 (from -r /opt/python/ondeck/app/requirements.txt (line 14)) Downloading https://files.pythonhosted.org/packages/47/1c/956fb482004f92f0b4978251a70142c11ba3ffb3f56a5ee9373efefaca8f/django-axes-2.3.3.tar.gz Collecting django-bootstrap3==9.0.0 (from -r /opt/python/ondeck/app/requirements.txt (line 15)) Downloading … -
Force password change on first login (Django)
A client requires the ability for managers to add users to a company (with a random one time password) where the user must change their password before accessing anything. I am developing the app in Django 2.2 I made a custom user, replacing username with an email address and I added a change_password bool flag to the user. My change_password form/function works properly, but redirecting does not. urls.py path('change-password/', views.change_password, name='change-password'), views.py class Login(LoginView): def form_valid(self, form): # form is valid (= correct password), now check if user requires to set own password if form.get_user().change_password: return HttpResponseRedirect(reverse('change-password')) else: auth_login(self.request, form.get_user()) return HttpResponseRedirect(self.get_success_url()) def change_password(request): if request.method == 'POST': form = PasswordChangeForm(data=request.POST, user=request.user) if form.is_valid(): form.save() request.user.change_password = False request.user.save() update_session_auth_hash(request, request.user) return redirect(reverse('user_view')) else: return redirect(reverse('change-password')) else: form = PasswordChangeForm(user=request.user) args = {'form': form} return render(request, 'users/change_password.html', args) The expected behavior is to redirect to change-password if the change_password flag is True, however, while the app does redirect to change-password, upon Submission the following error is thrown: NotImplementedError: Django doesn't provide a DB representation for AnonymousUser. If I add the decorator @login_required to my change_password function this error goes away, however, I am redirected back to the login page with … -
csv file going from 316 KB to ~3GB during django app run time then back instantly once app is terminated
The explanation is a bit long, but most of this is to give some background regarding my problem (the problem is probably not Python related, but having extra information wont hurt): I am currently working on a django application. The application window (browser) has two iframes each taking 50% of the screen. On the left-hand side there will be snopes (fact-check website) pages displayed and on the right-hand side one of the pages linked in that specific snopes article will be displayed. A form in the bottom of the app will let the user choose and post whether the RHS page is a source of the claim in the snopes article or not (there is also "invalid input" or "I dont know"). Submitting calls a function which tries to get the other links of the current snopes page, and if there is none, get any pages annotated (in this priority) twice, once, or least (so 0 then 3 then 4 .....). This is done by using a count.csv which simple stores how many each page+link combination has been annotated (as snopes articles can repeat and so can linked sites). The header of count.csv is : page source_url count The pages …