Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to update only field in drf
I'm trying to update a field of my model, im trying use patch for this, but i'm new to django rest and i think i'm having something wrong Im try use partial_update method but doesn't work. I want update status for canceled(canceled is in my enums.py ) This is part of my model class Aula(AcademicoBaseModel, permissions.AulaPermission): turma_disciplina = models.ForeignKey(TurmaDisciplina, models.PROTECT, related_name='lessons') data_inicio = models.DateTimeField(db_index=True) data_termino = models.DateTimeField() duracao = models.IntegerField(default=50) status = models.ForeignKey('Status', models.PROTECT, default=1) This is my view class CancelLessonView(generics.UpdateAPIView): serializer_class = serializers.AulaSerializer def patch(self, request, *args, **kwargs): lesson = self.kwargs.get('id') instance = models.Aula.objects.get(id=lesson) status = models.Status.objects.get(id=enums.StatusEnum.CANCELLED) instance.status.id = enums.StatusEnum.CANCELLED instance.status.name = status.name instance.status.color = status.color instance.status.ignore_in_attendance_report = status.ignore_in_attendance_report instance.status.allow_attendances = status.allow_attendances instance.status.allow_activities = status.allow_activities serializer = serializers.AulaSerializer(data=request.data, partial=True) serializer.is_valid(raise_exception=True) self.perform_update(serializer) instance.save() return Response(serializer.data) -
how to play audio using javascript , HTML , AJAX
I am trying to embed the audio player in my website . The requirement of this is when the user selects other page the audio should still play in the background unless user pause for it. I guess the terminology for this is Persistence audio player . not sure though. Can anyone provide some example how to achieve this one? I guess I have to use AJAX for this , if I am not wrong. Thank you -
How to only display one part of a class and iterate through it with a button
So basically I am basically trying to output one scene at a time in a story app. I have created a model that has a Story, Scene, and Choices. The Story has a title, and the scenes are related to the story via foreign-key, and the choices are related to the scenes via foreign-key. After finally being able to display all the scenes to their designated Story, and choices to their designated scene How would I be able to 1). Show only one scene at a time? Because the problem I'm facing is looping through them but it displays all the scenes and their possible choices under them but I would not like the user to see the next scene until they have answered so that when they hit submit if it has x boolean then I want it to either stop or continue the story depending on their answer 2). How do I show the choice they chose displayed with the next scene? I am really new to Django and trying my best to use class views as I've heard they are best in the long run of things but I don't understand how I would in this case? … -
How can I autofill author with a model form (video upload)
I need to tie the user to their post but 'author' is not included in the fields of the video upload form so I can't access the field when I save the form. When I add 'author' to the fields it gives a drop down box. (users shouldn't be able to post as anyone but themselves) I tried just listing the fields individually like so {{form.title}} to keep the author field but not show it to the user, it showed anyway. In the 'author' field of the VideoPost model I've tried changing out the null=True for these variants on default default=None, default=0, default='None', default=User, default=User.id where User = get_user_model() When I used default='None' the author dropdown box had the current users name in it, but still allowed a choice, when I tried to post it I got ValueError: invalid literal for int() with base 10: 'None' Also, in the views.py, I tried form = VideoPostForm(request.user,request.POST or None, request.FILES or None) and got CustomUser object has no .get() attribute and that was caused by form.save() I feel like this might be obvious to someone else but I've been staring at this code for a while now to figure it out.(a couple … -
Store extra information for product before adding to cart
tl;dr How do I change the context passed by the "Add to cart" button to add a different model instance that's a combination of that product and other information? I'm selling glasses, so while we have the product detail page showing the frame and frame variant (varying by color and size) information, the customer needs to also fill out a form for what type of lenses they want to get with that frame. One option could be to store each permutation of a frame variant and lenses combination as a frame variant in the database, like different storage options for smartphones, but I don't think that would be a good idea because: there are dozens of possible lens options the available lenses are essentially independent of the frame chosen it would be difficult to store information for the stock of frame variants if we only have frame variant + lenses objects. (I'm using the Django Shop 1.1, which adds managing stock.) Instead, I'm thinking of having a Glasses model with foreign keys to a frame variant and lenses, and this is what would be added to the cart. class Lenses(models.Model): material = models.CharField(choices=...) anti_reflective = models.CharField(choices=...) // ... class Glasses(models.Model): … -
calling opencv function on a django model object returning a TypeError?
I have a django project where users can upload images and these images can be processed by a function (made of some opencv functions). I want to save both the uploaded and the processed in a model.The processing function is called main. I tried using the function by running main(path_to_image.png) and it worked fine. so I tried doing this : models.py class UploadedImages(models.Model): patient = models.ForeignKey(Patient,on_delete=models.CASCADE,related_name='images') pre_analysed = models.FileField(upload_to = user_directory_path , verbose_name = 'Image') processed_image = models.ImageField(upload_to = user_directory_path ,blank=True, verbose_name = 'Image') views.py def AnalyseView(request,pk=None): patient = get_object_or_404(Patient,pk=pk) if request.method == 'POST': form = forms.ImageForm(request.POST,request.FILES) if form.is_valid(): image = form.save(commit=False) image.patient = patient image.processed_image= main(image.pre_analysed) messages.success(request,"image added successfully!") image.save() return HttpResponseRedirect(reverse_lazy('patients:patient_detail', kwargs={'pk' : image.patient.pk})) else: form = forms.ImageForm() return render(request, 'patients/analyse.html', {'form': form}) else: form = forms.ImageForm() return render(request, 'patients/analyse.html', {'form': form}) The error I get bad argument type for built-in operation -
How to calculate exact age from database birthday field and date.today()?
I have two dates 1. quarry set from database which includes date field (1992-11-15) 2. and a date.today() How can I subtract them to get exact age? Thanks a lot -
Ajax Request sometimes causes `XHR failed loading: POST` error
I am trying to run a simple Ajax Request to pass a JSON object from my Javascript file to my Python file in Django. However half the time, I get the error XHR failed loading: POST when I run it as follows: var csrf = $("[name=csrfmiddlewaretoken]").val() $.ajax({ type: "POST", url: "/fridge", data: { "fridgeitems": JSON.stringify(fridge), "csrfmiddlewaretoken": csrf }, dataType: "json", success: function(data) { console.log(data.data); }, }) In my python file: fridgeitems = request.POST['fridgeitems'] # do something with the data response_data = json.dumps(fridgeitems) return JsonResponse({"Success": True, "data": {"fridge": fridgeitems}}) The data I am trying to pass to my python file (fridgeitems) is a list. I am unsure what is wrong because the error doesn't happen all the time so please can someone tell me how to fix it. -
Django: Create profile page creates everything except Multiple Choice Field in the database
I am using the same form for profile_edit and create_profile functionality. It is updating the multi-choice values in the profile_edit page but does not create in create_profile. Below is the form code in forms.py class ProfileForm(ModelForm): full_name = forms.CharField(required=True) current_position = forms.CharField(required=True) about_me = forms.Textarea(attrs={'required':True}) topic_name = forms.ModelMultipleChoiceField(Topic.objects.all()) class Meta: model = Profile fields =( "full_name", "current_position", "about_me", "topic_name", ) Below is the views.py for profile creation def create_profile(request, user_id): if request.method == "POST": form = ProfileForm(request.POST) if form.is_valid(): form = form.save(commit=False) user = get_object_or_404(User, id=user_id) form.user = user print(form.topic_name.all()) # Prints empty queryset form.save() return redirect("profile_view", user_id=user_id) else: context = {"form": form} return render(request, "profile/create_profile.html", context) else: form = ProfileForm() context = { "form": form } return render(request, "profile/create_profile.html", context) Below is Model.py class Topic(models.Model): topic = models.CharField(max_length=12) def __str__(self): return self.topic class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True,) full_name = models.CharField(max_length=60, null=True) current_position = models.CharField(max_length=64, null=True) about_me = models.TextField(max_length=255, null=True) topic_name = models.ManyToManyField(Topic) def __str__(self): return self.full_name Both create_profile and edit_profile templates are exactly the same. It saves everything except Multichoice field. -
Make Django accept url with infinite parameters
I want to make Django accept url that consists of infinite number of parameters. Something like dropbox has going on. Each parameter for each folder the file is in. There could be infinite number of subfolders. Parameter is alphanumeric. -
how to make a register page accept only one email address
i just want to know how to make a register page accept one email address i have not tried anything yet def register(request): enter code hereif request.method == 'POST': enter code hereform = UserRegisterForm(request.POST) enter code hereif form.is_valid(): enter code hereform.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) I want the register page to accept only one email address so it is used only once to register -
How to fix django-markdown issue in django-admin form
I'm making Blog app in Django and want to add Django-Markdown Field in Admin site for Posts model which holds data for blog posts. Which changings I have to need to do in the following code? I am using Django:2.2.4 and Django-Markdown-App: 0.9.6 Here is my Post Model ONE = 1 TWO = 2 status_choices = ( (ONE, 'draft'), (TWO, 'published') ) class Posts(models.Model): title = models.CharField(max_length=255, blank=False) content = MarkdownField() created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) author = models.ForeignKey( User, on_delete=models.CASCADE ) status = models.IntegerField(choices=status_choices, default=ONE) slug = models.SlugField(max_length=255) def __str__(self): return self.title class Meta: verbose_name = "Post" verbose_name_plural = "Posts" Here is admin.py code from django.contrib import admin from .models import Posts from django_markdown.admin import MarkdownModelAdmin # Register your models here. class PostsAdmin(MarkdownModelAdmin): prepopulated_fields = {'slug': ('title',)} admin.site.register(Posts, PostsAdmin) Here is settings.py INSTALLED_APPS = [ ......, 'django_markdown', ......, ] MARKDOWN_EDITOR_SKIN = 'markitup' Here is Project level urls.py urlpatterns = [ ....... path('markdown/', include('django_markdown.urls')), ....... ] I am expecting to display a markdown interface in the admin site instead of a simple text field, but the current output is a simple text field. -
In Django, how can I easily inherit a field and create a new class with this field preconfigured parameters?
I am currently using UUID in my PostgreSQL database, therefore I am also using PrimaryKeyRelatedField() with some parameters in order to avoid problems when encoding to JSON the UUID field. My serializer field looks like: id = serializers.PrimaryKeyRelatedField(read_only=True, allow_null=False, pk_field=serializers.UUIDField(format='hex_verbose')) And in every serializer that uses UUID I am having to use that. My question is, how can I create a new class based on PrimaryKeyRelatedField so that I don't have to write all those parameters (read_only, allow_null...) ? I am looking for something like: id = BaseUUIDField() Thanks -
How can I override a method in python open-id package using django?
I used mozilla-django-oidc for my sso. Everything is okay but the problem is, I'm using keycloak auth for my open-id. This mozilla oidc package has only allowed that individual users who has an email address, only then it will be verified claim. But, in my keycloak I've not kept any user email address, it's optional, for this reason, the user having no email address, creates this error after redirection: failed to get or create user: Claims verification failed but if the user has email, then it's working fine. After reading their documentation I've understood that I've to override this method probably: def verify_claims(self, claims): """Verify the provided claims to decide if authentication should be allowed.""" # Verify claims required by default configuration scopes = self.get_settings('OIDC_RP_SCOPES', 'openid email') if 'email' in scopes.split(): return 'email' in claims LOGGER.warning('Custom OIDC_RP_SCOPES defined. ' 'You need to override `verify_claims` for custom claims verification.') return True i want to keep only custom scope here like this: OIDC_RP_SCOPES = 'openid' but for this I've to override the verify_claims method. But my problem is that where should I call this override function? will this be in my settings.py or it'll be in my views.py? This is how I … -
Customer viewer count doubles once I refresh my django webpage
I am new to Django and I tried implementing a viewer count functionality on a website i'm working on. It seemed to be working well at first but i realised that when i refreshed a page the count added twice as opposed to once. What might be the problem? I am using class based views. class IdeaDetailView(DetailView): model = Ideas template_name = 'strathideasapp/ideas_detail.html' def get_object(self): object = super(IdeaDetailView, self).get_object() object.view_count += 1 object.save() return object -
How to Serve Django Applications with Apache2
I want to serve my Django applications with Apache2 over HTTPS. However, I am very new to server development and have never worked with Apache before. I have started a basic configuration file, but I am unsure as to what I am missing or incorrectly configuring. When I try to access my site over HTTPS I receive the following error: You're accessing the development server over HTTPS, but it only supports HTTP.. I have placed my certificate and certificate chain files at /etc/ssl/certs/ and my private key at /etc/ssl/private/. Please let me know if any other information is needed. Any help is greatly appreciated. 000-default.conf <VirtualHost *:443> ServerName www.my_domain.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined SSLEngine on SSLCertificateFile /etc/ssl/certs/_.certificate.csr SSLCertificateKeyFile /etc/ssl/private/_.privatekey.key SSLCertificateChainFile /etc/ssl/certs/certificatechain.csr Alias /static/ /home/user/myproject/static <Directory /home/user/development/mysite/mysite/static> Require all granted </Directory> <Directory /home/user/development/mysite/mysite> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess mysite python-path=/home/user/myproject python-home=/home/user/development/venv WSGIProcessGroup mysite WSGIScriptAlias / /home/user/development/mysite/mysite/wsgi.py </VirtualHost> -
How to Correctly Use JsonResponse to Handle Ajax Request
I am trying to use JsonResponse to return data for a successful Ajax request but am unsure how to format the data. data = request.POST[data_from_javascript] # do something with data return JsonResponse(?) I want to send back the data to the Javascript code and say that it was successful so it can run the success function but am unsure how to correctly do so. -
collectstatic --clear skipping instead of deleting
I am trying to update admin static files after upgrading to Django 2.2, but when I run python3 ./manage.py collectstatic --clear --verbosity 3, I see the following output: Skipping 'admin/css/base.css' (not modified) Skipping 'admin/css/changelists.css' (not modified) Skipping 'admin/css/dashboard.css' (not modified) Skipping 'admin/css/forms.css' (not modified) Skipping 'admin/css/ie.css' (not modified) Skipping 'admin/css/login.css' (not modified) ... I would think that using the --clear option would prevent skipping any files. How can I force delete? These static files are served on AWS S3. I am able to update modified static files just fine, and the --clear option worked prior to the upgrade. I am using the following relevant packages: Django==2.2.3 django_storages==1.7.1 boto==2.49.0 settings.py from boto.s3.connection import OrdinaryCallingFormat ########## AWS CONFIGURATION AWS_STORAGE_BUCKET_NAME = 'xxxxx' AWS_S3_REGION_NAME = 'xxxxx' AWS_S3_CALLING_FORMAT = OrdinaryCallingFormat() AWS_S3_CUSTOM_DOMAIN = '%s' % AWS_STORAGE_BUCKET_NAME AWS_S3_HOST = 's3-%s.amazonaws.com' % AWS_S3_REGION_NAME STATIC_ROOT = normpath(join(SITE_ROOT, 'assets')) STATICFILES_DIRS = ( normpath(join(SITE_ROOT, 'static')), ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', #'django.contrib.staticfiles.finders.AppDirectoriesFinder', #causes verbose duplicate notifications in django 1.9 ) STATICFILES_LOCATION = 'static' STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION) STATICFILES_STORAGE = 'custom_storages.StaticStorage' -
How to define a foreign key dynamicaly with abstract=True or Mixin?
I want to define a foreign key with a dynamic related_name. All the childs have the same parent. class AbstractChild(models.Model): class Meta: abstract=True related_name = None def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.parent = models.ForeignKey( Parent,on_delete=models.CASCADE, related_name=self.related_name ) self.created_at = models.DateTimeField(auto_now_add=True) class Child2(AbstractChild): #this should create the foreign key with the dynamic related_name related_name="child2" What should be the way for this? Mixin or abstract model? -
How to refresh an item in a flatList when like action happened?
So I have a flatList that gets data from an API. It does not refresh itself automatically not even with extraData. So I just want that the picture on that post changes to the LIKED picture. I already tried that in the likeAction function inside the StandardPostView that it gets refreshed by the response data, but then all the new / or next posts got the same LIKED picture. constructor(props) { super(props); this.state = { gestureName: 'none', hasLiked: this.props.has_liked, count:this.props.likes, current_user:"", modalVisible: false, dropdown:"", }; } likeAction = () => { axios.get(URL+'/api/posts/like/'+this.props.post_id, {headers: {'Authorization':'Token '+this.props.jwt}}) .then((response) => { }).catch((error) => { this.setState({ error: 'Error retrieving data', }); }); } return ( <Text style={styles.date}>{format(new Date(this.props.date), 'MMMM Do, YYYY')}</Text> <View style={styles.likeSection}> <TouchableOpacity onPress={this.likeAction}> <Image style={styles.likeImage} source={image_url}/> </TouchableOpacity> <TouchableOpacity onPress={this.props.goToUser}> <Image source={require("../icons/share.png")} style={styles.share}/> </TouchableOpacity> </View> </View> ); } } <StandardPostView current={this.state.user} author_id={item.author.id} username={item.username} title={item.title} content={item.content} image={{uri:item.author.profile_image}} date={item.date_posted} handleRefresh={this.handleRefresh} likes={item.likes} post_id={item.id} jwt = {this.props.screenProps.jwt} refresh = {this.handleRefresh} has_liked = {item.has_liked} editPost={() => this.props.navigation.navigate('EditPost',{ title:item.title, content:item.content, post_id:item.id })} goToProfile={() => this.props.navigation.navigate('UserProfile', { user_id:item.author.user })} goToPost={() => this.props.navigation.navigate('SinglePost', { post_id:item.id })} goToPostLike={() => this.props.navigation.navigate('PostLikes', { post_id:item.id, title:"Likes" })} goToUser={()=> this.props.navigation.navigate('ChooseUser',{ post_id:item.id })} /> )} /> -
Django doesn't change html when changing route
I created several html's for each project functionality, but when I change route, html doesn't change. The only html that appears is the homepage, index.html. urls.py: from website.views import IndexTemplateView, FuncionarioListView, FuncionarioUpdateView, FuncionarioCreateView, FuncionarioDeleteView from django.conf.urls import patterns, include, url app_name = 'website' urlpatterns = [ # GET / url('', IndexTemplateView.as_view(), name="index"), # GET /funcionario/cadastrar url('funcionario/cadastrar', FuncionarioCreateView.as_view(), name="cadastra_funcionario"), # GET /funcionarios url('funcionarios/', FuncionarioListView.as_view(), name="lista_funcionarios"), # GET/POST /funcionario/{pk} url('funcionario/<pk>', FuncionarioUpdateView.as_view(), name="atualiza_funcionario"), # GET/POST /funcionarios/excluir/{pk} url('funcionario/excluir/<pk>', FuncionarioDeleteView.as_view(), name="deleta_funcionario"), ] views.py: # -*- coding: utf-8 -*- from django.core.urlresolvers import reverse_lazy from django.views.generic import TemplateView, ListView, UpdateView, CreateView, DeleteView from helloworld.models import Funcionario from website.forms import InsereFuncionarioForm # PÁGINA PRINCIPAL # ---------------------------------------------- class IndexTemplateView(TemplateView): template_name = "website/index.html" # LISTA DE FUNCIONÁRIOS # ---------------------------------------------- class FuncionarioListView(ListView): template_name = "website/lista.html" model = Funcionario context_object_name = "funcionarios" # CADASTRAMENTO DE FUNCIONÁRIOS # ---------------------------------------------- class FuncionarioCreateView(CreateView): template_name = "website/cria.html" model = Funcionario form_class = InsereFuncionarioForm success_url = reverse_lazy("website:lista_funcionarios") # ATUALIZAÇÃO DE FUNCIONÁRIOS # ---------------------------------------------- class FuncionarioUpdateView(UpdateView): template_name = "website/atualiza.html" model = Funcionario fields = '__all__' context_object_name = 'funcionario' success_url = reverse_lazy("website:lista_funcionarios") # EXCLUSÃO DE FUNCIONÁRIOS # ---------------------------------------------- class FuncionarioDeleteView(DeleteView): template_name = "website/exclui.html" model = Funcionario context_object_name = 'funcionario' success_url = reverse_lazy("website:lista_funcionarios") and an example of one of the … -
Django Database Router not working properly
I have the following DB router, located in proj/inventory/inventory_router.py: class Inventory_Router: def db_for_read(self, model, **hints): if model._meta.app_label == 'webhooks' or model._meta.app_label == 'auth': return 'default' elif model._meta.app_label == 'inventory': return 'user_0001' else: return None def db_for_write(self, model, **hints): if model._meta.app_label == 'webhooks' or model._meta.app_label == 'auth': return 'default' elif model._meta.app_label == 'inventory': return 'user_0001' else: return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'auth' or obj2._meta.app_label == 'auth': return True else: return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == 'webhooks' or app_label == 'auth': return db == 'default' elif app_label == 'inventory': return True else: return None and the Product model for the inventory app, proj/inventory/models.py: from django.db import models class Product(models.Model): ... class Meta: app_label = 'inventory' My settings.py: DATABASE_ROUTERS = [ 'inventory.inventory_router.Inventory_Router', ] DATABASE_APPS_MAPPING = { # not sure if I need this? 'auth':'default', } DATABASES = { 'default': { 'ENGINE':'django.db.backends.mysql', 'NAME':'account', 'USER':'root', 'PASSWORD':'password', 'HOST':'localhost', 'PORT':'3306' }, 'user_0001': { 'ENGINE':'django.db.backends.mysql', 'NAME':'user_0001', 'USER':'user_0001', 'PASSWORD':'password', 'HOST':'localhost', 'PORT':'3306' }, ... } I am trying to have all models from the inventory app only create tables in the user_0001 schema, and not in the default account schema. When I run python3 manage.py migrate, the default schema, account, … -
One week imposible to Deploy django in windows with apache
500 Internal Server Error is what I have all the time. Hello guys I’m trying to deploy django with apache server in Windows Without any success, Any help is welcome. pro1.local is already setup in host and Works fine. WSGI is perfectly installed. mod_wsgi-express module-config LoadFile "c:/program files (x86)/python37-32/python37.dll" LoadModule wsgi_module "c:/program files (x86)/python37-32/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win32.pyd" WSGIPythonHome "c:/program files (x86)/python37-32" Httpd.conf LoadFile "c:/program files (x86)/python37-32/python37.dll" LoadModule wsgi_module "c:/program files (x86)/python37-32/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win32.pyd" WSGIPythonHome "c:/program files (x86)/python37-32" Httpd-vhost.conf # Virtual Hosts # # Required modules: mod_log_config # If you want to maintain multiple domains/hostnames on your # machine you can setup VirtualHost containers for them. Most configurations # use only name-based virtual hosts so the server doesn't need to worry about # IP addresses. This is indicated by the asterisks in the directives below. # # Please see the documentation at # <URL:http://httpd.apache.org/docs/2.4/vhosts/> # for further details before you try to setup virtual hosts. # # You may use the command line option '-S' to verify your virtual host # configuration. # # VirtualHost example: # Almost any Apache directive may go into a VirtualHost container. # The first VirtualHost section is used for all requests that do not # match a ServerName or ServerAlias … -
Celery worker getting crashed on Heroku
I am working on a Django project which I have pushed on Heroku, for background tasking I have used Celery. Although Celery works fine locally, but on the Heroku server I have observed that celery worker is getting crashed. I have set CLOUDAMQP_URL properly in settings.py and configured worker configuration in Procfile, but still worker is getting crashed. Procfile web: gunicorn my_django_app.wsgi --log-file - worker: python manage.py celery worker --loglevel=info Settings.py ... # Celery BROKER_URL = os.environ.get("CLOUDAMQP_URL", "django://") #CELERY_BROKER_URL = 'amqp://localhost' BROKER_POOL_LIMIT = 1 BROKER_CONNECTION_MAX_RETRIES = 100 CELERY_TASK_SERIALIZER="json" CELERY_RESULT_SERIALIZER="json" CELERY_RESULT_BACKEND = "amqp://" Logs 2019-08-05T15:03:51.296563+00:00 heroku[worker.1]: State changed from crashed to starting 2019-08-05T15:04:05.370900+00:00 heroku[worker.1]: Starting process with command `python manage.py celery worker --loglevel=info` 2019-08-05T15:04:06.173210+00:00 heroku[worker.1]: State changed from starting to up 2019-08-05T15:04:09.067794+00:00 heroku[worker.1]: State changed from up to crashed 2019-08-05T15:04:08.778426+00:00 app[worker.1]: Unknown command: 'celery' 2019-08-05T15:04:08.778447+00:00 app[worker.1]: Type 'manage.py help' for usage. 2019-08-05T15:04:09.048404+00:00 heroku[worker.1]: Process exited with status 1 -
Using django-user-accounts with costom PasswordChangeView - Rediect Error
I'm setting up a django project and I need a user-management-system that follow our user policy. It needs to force the user to change the password after 180 days. So I decided to use pinax/django-user-accounts. I have a own django app named 'accounts' that customize the standard django auth behaviour - essantially defining custom templates. When the password expires, django redirects to /accounts/change-password/?next=account_password and so it loops and a browser redirect error shows up in my Firefox. I setup django-user-accounts: ACCOUNT_PASSWORD_EXPIRY = 60*60*2 # seconds until pw expires ACCOUNT_PASSWORD_USE_HISTORY = True ACCOUNT_LOGIN_URL = 'accounts:login' ACCOUNT_LOGOUT_REDIRECT_URL = 'accounts:logout' ACCOUNT_PASSWORD_CHANGE_REDIRECT_URL = 'accounts:account_password' SITE_ID = 1 I also tried to hardcode the ACCOUNT_PASSWORD_CHANGE_REDIRECT_URL to '/accounts/change-password'. The result was the same. The login_required-decorator was changed from django.contrib.auth.decorators to account.decorators. The urls.py of my accounts app is: app_name = 'accounts' urlpatterns = [ ... path( 'change-password/', MyPasswordChangeView.as_view(), name='account_password' ), ] I'm created my own password change view inherits from django.contrib.auth.views.PasswordChangeView: class MyPasswordChangeView(PasswordChangeView): template_name = 'accounts/password_change.html' def get_success_url(self): return '/' The goal is to show up the change-password/ page on every request if the password is expired. It allready tries to get there, but ends up in this redirect loop.