Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to solve circular imports
I have 2 models ai_output which defines AIOutput and manual_overwrite with ManualOverwrite which are both importing each other and so I get the following error: from main.models.manual_overwrite import ManualOverwrite ImportError: cannot import name ManualOverwrite The only solution I could find through the django docs was solving it by removing the import of a class in one of the files, and replacing it with a string containing the name of the class and so this: aioutput = models.ForeignKey(AIOutput, null=True, blank=True) became this: aioutput = models.ForeignKey('ai_output.AIOutput', null=True, blank=True) But now I get that: main.ManualOverwrite.aioutput: (fields.E300) Field defines a relation with model 'ai_output.AIOutput', which is either not installed, or is abstract. Any idea how to solve the issue with circular imports? Any tip would be greatly appreciated! -
Purpose of using virtual environment
Is the primary purpose of using a virtual environment to control versions of various packages installed on your development machine? For example, I am developing a webapp using Django. My assumption is that using a virtual environment like Pipenv will ensure I don't have any problems down the road if I update my Django or python versions on my computer, because the webapp project is isolated with it's own versions of Django and Python. Are there any other notable benefits to using Pipenv? -
UnboundLocalError when I want to export in django
I recived this error: local variable 'obj' referenced before assignment def export_filename(self, file_format, person): try: obj = models.Home.online.get(id=person) except Exception: pass return '{}.{}.{}.{}'.format(obj.id, slugify(obj.title), obj.date.strftime('%Y%m%d'), file_format.get_extension()) -
Django sqlite development to production
I am having trouble understanding how to synchronise my development and production environments. I have a production and development branch in git, with the production branch being of course what the server's copy is. My sqlite database is currently under version control (which I now gather it shouldn't be, however I am not sure how I would sync my copies of the project if it wasn't?) When I want to make a change I commit and push the server's copy to production and then I pull that down to my local machine. I then make a change (which can include database changes), but then in terms of getting those changes back into production, I am not sure how to get the changes back onto my server without potentially overwriting changes that have occurred on the server since I started the change? How can I handle local changes to the database when changes may also have occurred on the server at the same time? I have been searching for a while and thought that maybe South was for that kind of problem but I gather that it is an old solution. Thanks for your help -
how to retrieve password in django 2.0?
Im using ldap for user authentication in django 2.0, and i need to create an endpoint to authenticate user from another application just passing the username to then redirect them. Isnt yet something to retrieve the raw password? -
Django How to get the id from a ModelChoiceField?
I am new to Django and can't figure out a solution for my problem. I don't know if it is related to my understanding on how Django works or if Django does not allow it... My problem is I can't access the id value of my object "TypeEngine". In my example if I select "SQL SERVER" or "POSTGRES" the value I get is "SQL SERVER" or "POSTGRES" but not 1 or 2. When trying to assign server.type_engine = server_form.cleaned_data['type_engine'] I have this error : Cannot assign "(<TypeEngine: SQL SERVER 2016 13.0.4001.0>,)": "Server.type_engine" must be a "TypeEngine" instance. Thanks you for your help ! My two models : class TypeEngine(models.Model): class Meta: managed = False db_table='type_engine' id = models.IntegerField(primary_key=True, db_column='id') engine_name = models.CharField(max_length=15, db_column='engine_name') engine_version = models.CharField(max_length=15, db_column='engine_version') talend_connector_id = models.IntegerField(db_column='talend_connector_id') engine_major_version = models.CharField(max_length=15,db_column='engine_major_version') def __str__(self): return self.engine_name + " " + self.engine_major_version + " " + self.engine_version class Server(models.Model): class Meta: managed = False db_table='server' id = models.AutoField(primary_key=True, db_column='id') name = models.CharField(max_length=200, db_column='server_name') ip_address = models.CharField(max_length=15, db_column='server_ip') port = models.IntegerField(db_column='server_port') user = models.CharField(max_length=50, db_column='user_login') type_engine = models.ForeignKey(TypeEngine, on_delete=models.PROTECT, db_column='id_type_engine') password = models.BinaryField( db_column='crypted_user_passwd') flux = models.BooleanField(db_column='flux') def __str__(self): return self.name I have an object form : class ServerForm(forms.Form): def __init__(self, … -
Employee Information Management
I am developing a employee portal in which each individual user can update his information, after successfully registering and logging from their accounts. So after logging inside I want user to update their information for each user separately. Mr X can't see the details of Mr. Y accounts.If anyone can please help me with this. Forms.py from django import forms User = get_user_model() class RegisterForm(forms.Form): username = forms.CharField(widget = forms.TextInput( attrs = {"class":"form-control", "placeholder":"Username" }),label='') email =forms.EmailField(widget = forms.TextInput( attrs = {"class":"form-control", "placeholder":"Email" }),label='') password = forms.CharField(widget =forms.PasswordInput(attrs = {"class":"form-control", "placeholder":"Password" }),label='') password2 = forms.CharField(label ='' , widget = forms.PasswordInput(attrs = {"class":"form-control", "placeholder":"Confirm Password" })) def clean_email(self): email = self.cleaned_data.get('email') qs = User.objects.filter(email =email) if qs.exists(): raise forms.ValidationError("Email is already taken") return email def clean_username(self): username = self.cleaned_data.get('username') qs =User.objects.filter(username=username) if qs.exists(): raise forms.ValidationError("Name is already taken") return username def clean(self): data =self.cleaned_data password = self.cleaned_data.get('password') password2 = self.cleaned_data.get('password2') if password2!= password: raise forms.ValidationError("Password must match") return data class LoginForm(forms.Form): username = forms.CharField(widget = forms.TextInput( attrs = {"class":"form-control", "placeholder":"Username" }),label='') password = forms.CharField(widget =forms.PasswordInput(attrs = {"class":"form-control", "placeholder":"Password" }),label='') views.py User = get_user_model() def register_view(request): form = RegisterForm(request.POST or None) context = {"form":form} if form.is_valid(): username = form.cleaned_data['username'] email = form.cleaned_data['email'] … -
Django redirecting NoReverseMatch
Any help would be greatly appreciated. I am tearing my hair out trying to understand why I am getting NoReverseMatch error. I am trying to get it to add a participant and return to the list of participants on the particular study. I am also trying to get a back button working but I also get a NoReverseMatch error. Urls urlpatterns = [ path('', views.homepage, name='homepage'), path('studies/', views.studylist, name='studylist'), path('studies/add_study', views.add_study, name='add_study'), path('studies/<int:id>', views.study_update, name='study_edit'), path('studies/<int:id>/participants', views.participantlist, name='participantlist'), path('studies/<int:id>/participants/add_participant', views.add_participant, name='add_participant')] Views def participantlist(request, id): participant_list = Participant.objects.filter(study_id=id) return render(request, 'databank/participants.html', {'participantlist':participant_list, 'study_id':id}) def add_participant(request, id): if request.method == "POST": form = ParticipantForm(request.POST) if form.is_valid(): participant_item = form.save(commit=False) participant_item.study_id = id participant_item.save() return HttpResponseRedirect(reverse('participantlist', args=(id,))) else: form = ParticipantForm() return render(request, 'studies/add_participant.html', {'form': form}) Template <!DOCTYPE html> <html> <head> <title>Study Participant</title> </head> <body> <h1>Add or Edit Participant</h1> <p>Please fill in the required information and click save to add a participant</p> <form method="POST" action=" "> {% csrf_token %} <table> {{ form }} </table> <br> <input type="submit" value="Save"> </br> </form> <br /> <form action="{% url 'participantlist' %}"> <input type="submit" value="Back" /> </form> </body> </html> NoReverseMatch Reverse for 'participantlist' with arguments '('',)' not found. 1 pattern(s) tried: ['studies/(?P<id>[0-9]+)/participants$'] -
Building a backend consisting of a database and API for a website and mobile app
I'm looking to build an online platform consisting of a website and mobile app; which communicate with a backend consisting of a database and API. The backend will be hosted on AWS or Google Cloud, it must be scalable to support millions of users, handle user authentication and be secure enough to handle personal and transactional data. I'm a mobile app developer so will be developing the mobile app natively for both iOS and Android. I have previously developed apps that have communicated with RESTful APIs and used Swagger so would definitely like to incorporate these. I'm looking for suggestions and advice for frameworks and languages which would best suit my use case which I can then research myself. Any tutorials would be great too. I'm familiar with python and Django however django supports the web app model rather than the more modern separate backend and front end approach. Any suggestions would be much appreciated. Thanks, Sami. -
How to setup a sequence for an attribute while using create_batch in factory-boy?
When using factory_boy in Django, how can I achieve this? models.py class TestModel(models.Model): name = CharField() order = IntegerField() recipes.py class TestModelFactory(factory.django.DjangoModelFactory): class Meta: model = TestModel name = factory.LazyAttribute(lambda o: faker.word().title()) parent = 0 tests.py recipes.TestModelFactory.create_batch(4, order=+10) or recipes.TestModelFactory.create_batch(4, order=seq(10)) or something along those lines, to achieve this result: TestModel.objects.all().values_list('order', flat=True) [10, 20, 30, 40] -
Django context processor being called twice per request
I've found only one topic like this and not a single answer in there seems to work. I have two context proccesors: def cart_view(request): try: cart_id = request.session['cart_id'] cart = Cart.objects.get(id=cart_id) request.session['total'] = cart.items.count() print('OLD CART USED') except: cart = Cart() cart.save() cart_id = cart.id request.session['cart_id'] = cart_id cart = Cart.objects.get(id=cart_id) print('NEW CART CREATED') return {'cart':cart} # dropdown menu categories to every page def categories(request): print('CATEGORIES CONTEXT PROCCESOR') categories = Category.objects.all() return {'dropdown_categories':categories} Via those print statements I'm able to see that each one of those CP being executed twice per request, although I'm rendering just base.html. What may be the problem? P.S. I know that I'm querying the DB every time I use CP, I'll add caching later. -
django.db.utils.ProgrammingError while try manage.py makemigrations on app which is cloned from github
I have a problem with migration database from cloned django project to postresql db. os is ubuntu server 18.04 installed python3-pip python3-dev libpq-dev postgresql postgresql-contrib nginx. setup postgresql db, upgrade pip3, install virtualenv, create /opt/projectdir. Inside projectdir create virtualenv moviesenv and activate it, install django, gunicorn and psycopg2 with pip create directory movies, then inside directory movies typed: git clone https://username/reponame . setup allowed hosts and db sections. typed manage.py makemigrations and recive error message psycopg2.ProgrammingError: relation "movie_movie" does not exist django.db.utils.ProgrammingError: relation "movie_movie" does not exist this is only small piece of error output but I dont wanna paste all here. If anyone could help please. -
Django CreateView self.object retuning None
I've a CreateView in Django and I'm trying to use the object created as follows. def get_success_url(self, *args, **kwargs): team = self.get_team() match = self.object if match.home_team.team == team: lineup = match.home else: lineup = match.away return redirect ('matches:update-lineup', kwargs={'pk' : lineup.id}) I simply get an error that self.object is None. I think this means the object hasn't been saved yet so how do I implement get_success_url to wait until the object is saved and then use it? -
How get the Html-Ajax post array value like below stucture in dijango view.py?
Form: <form id="form"> <input type="text" name="group_name"> <div id="dynamic_form"> <input type="text" name="members[0][name]"> <input type="text" name="members[0][date]"> <input type="text" name="members[1][name]"> <input type="text" name="members[1][date]"> <input type="text" name="members[2][name]"> <input type="text" name="members[2][date]"> </div> Expected Output: "{ "group_name": "SomeGroup", "members": [ { "name": "Alice", "date": "01/01/2015" }, { "name": "Bob", "date": "02/01/2015" }, { "name": "Carol", "date": "03/01/2015" }, ] }" -
Django, Use style from database
In my database is style (here is models.py) and I wanna used it in template, but I don't know how. (I know how to use styles saved in "static" directory) I'm using django 2.1, and python 3.7. -
Django form cleaning acting strangely
I am overwriting clean method but when I do it like this: def clean(self): if "post_update_password" in self.data: print(self.cleaned_data) old_password = self.cleaned_data['old_password'] new_password1 = self.cleaned_data['new_password1'] new_password2 = self.cleaned_data['new_password2'] return super().clean() It returns this: {'old_password': 'Password,1.', 'new_password1': 'a'} which means that I am unable to get that new_password2 value. And when I change my clean method like this: def clean_new_password2(self): if "post_update_password" in self.data: print(self.cleaned_data) old_password = self.cleaned_data['old_password'] new_password1 = self.cleaned_data['new_password1'] new_password2 = self.cleaned_data['new_password2'] return super().clean() It magicly works and returns: {'old_password': 'Password,1.', 'new_password1': 'PAssssad', 'new_password2': 'a'} I don't really understand what is happening. I know how to bypass this issue but I am really curious where is the problem. Thanks for any reply -
Django: posting to foreign keys results in matching query does not exist
Models: class CompanyList(models.Model): company_id = models.CharField(max_length=10, unique=True) company_name = models.CharField(max_length=100, unique=True) class Reporting(models.Model): company = models.ForeignKey(CompanyList, on_delete=models.CASCADE) year_end = models.DateField() class CompanyAccountsExtracts(models.Model): reporting = models.ForeignKey(Reporting, on_delete=models.CASCADE) data_type = models.CharField(max_length=30) source = models.CharField(max_length=30) value = models.CharField(max_length=30) Now I have a pandas dataframe (company_accounts_extracts_upload) of data to write to CompanyAccountsExtracts. I am using the following code to do so: for i, row in enumerate(company_accounts_extracts_upload.values): single_row = company_accounts_extracts_upload.iloc[i].to_dict() report = models.Reporting.objects.get(company=single_row['Company ID Number'], year_end=single_row['Year End']) DataExtract = models.CompanyAccountsExtracts(reporting=report, data_type=single_row['DataType'], source=single_row['Source'], value=single_row['Value'], ) DataExtract.save() I am getting the following error on the "report = models.Reporting..." line: DoesNotExist: Reporting matching query does not exist. However, I'm 100% sure the company and year end does exist as I can see it in the admin view. I think the error might be related to how I am posting to a foreign key as the Reporting foreign key which again is a foreign key from CompanyList? -
Django Groupby doing with many
To better understand: Just look at the Django queryset and MYSQL GroupBy, I want group by only si__c_id and spm_id I have: reset_queries() df = pd.DataFrame(list(MyModel.objects .values('si__c_id', 'spm_id') ----- in groupby .annotate(tq=Sum('q'), avg_d=Avg('d')) .values('id', 'si_id', 'sp', ------ id in groupby 'tq', 'avg_d', c_id =F('some_foreign_key'), -- with F in groupby pt_id =F('some_foreign_key'), -- with F in groupby c_d =F('some_foreign_key'), -- with F in groupby p_id =F('some_foreign_key'), -- with F in groupby sbt_id=F('some_foreign_key'),) -- with F in groupby .order_by('-tq'))) print(connection.queries) And when I look at the query generated it is: SELECT `some_table`.`id`, `some_table`.`si_id`, `some_table`.`sp`, SUM(`some_table`.`q`) AS `tq`, AVG(`some_table`.`q`) AS `avg_d`, `some_table`.`c_id` AS `c_id`, `some_table`.`pt_id` AS `pt_id`, `some_table`.`d` AS `c_d`, `some_table`.`mp_id` AS `p_id`, `some_table`.`bt_id` AS `sbt` FROM `sib` INNER JOIN `some_table` ON (some_condition) LEFT OUTER JOIN `some_table` ON (some_condition) INNER JOIN `some_table` ON (some_condition) INNER JOIN `some_table` ON (some_condition) ---------------------------------------- look down here.. GROUP BY `some_table`.`id`, -- id in 2nd values `some_table`.`c_id`, `some_table`.`pt_id`, `some_table`.`c_d`, `some_table`.`p_id`, `some_table`.`sbt_id` ORDER BY `tq` DESC Basically the code is long and also I have changed the names, which makes it hard to understand, so in short description is: What by now I have learnt is what model.object.values().annotate().values() does is group-by first values() does annotate and give us back … -
How to save the task name in extended django_celery_result model
I have two task in celery.py. from __future__ import absolute_import, unicode_literals from celery import Celery from celery.schedules import crontab import os from . import celeryconfig from django.conf import settings from celery_tasks import scripts # from django.db import models # from django_celery_results.models import TaskResult os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Etl_ui.settings') app = Celery('Etl_ui') app.config_from_object(celeryconfig) app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task(900.0,task_ssl_extract.s(),name='add every 15 minmutes') sender.add_periodic_task(300.0,task_ssl_transform.s(),name='add every 5 minutes') #sender.add_periodic_task(30.0, test2.s('world'), expires=10) @app.task(max_retries=5,default_retry_delay=300,name='ssl_extract') def task_ssl_extract(): from celery_tasks.scripts.ssl_extract import main main(username, password, brandname, client_name, partner, path) @app.task(name='ssl_transform') def task_ssl_transform(): from celery_tasks.scripts.ssl_transform import main main(input_file, output_file, url, username, password, error_file) I am using django_celery_results as backend which save the task result with many fields. But this model does not have task_name column. I extended the model DjangoCeleryResultsTaskresult of django_celery_results in models.py. class TaskResultsExtension(models.Model): task_name = models.CharField(max_length=255) task = models.OneToOneField(DjangoCeleryResultsTaskresult,on_delete=models.CASCADE) I created a task in tasks.py. from __future__ import absolute_import, unicode_literals from celery.decorators import task from .models import TaskResultsExtension, DjangoCeleryResultsTaskresult @task(name="save the new task") def save_task(): task_result = DjangoCeleryResultsTaskresult.objects.all() So I want to save the task name of each task in celery.py when one of the task runs with its task_id and task_name in the extended model TaskResultsExtension. I am using python3 and django 1.11. Please help me with … -
Gunicorn not found in virtualenv
I'm deploying a django application and it works fine when I run it manually. I'm trying to use supervisor but when I run sudo supervisorctl status botApp the log file says: Starting botApp as ubuntu /home/ubuntu/gunicorn_start.bash: line 28: exec: gunicorn: not found My gunicorn_start.bash is the following one: #!/bin/bash NAME="botApp" # Name of the application DJANGODIR=/home/ubuntu/chimpy # Django project directory SOCKFILE=/home/ubuntu/django_env/run/gunicorn.sock # we will communicte using this unix socket USER=ubuntu # the user to run as GROUP=ubuntu # the group to run as NUM_WORKERS=3 # how many worker processes should Gunicorn spawn DJANGO_SETTINGS_MODULE=botApp.settings # which settings file should Django use DJANGO_WSGI_MODULE=botApp.wsgi # WSGI module name echo "Starting $NAME as `whoami`" # Activate the virtual environment cd $DJANGODIR source /home/ubuntu/django_env/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH # Create the run directory if it doesn't exist RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR # Start your Django Unicorn # Programs meant to be run under supervisor should not daemonize themselves (do not use --daemon) exec gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ --bind=unix:$SOCKFILE \ --log-level=debug \ --log-file=- And my configuration file in /etc/supervisor/conf.d/botApp.conf is: [program:botApp] command = /home/ubuntu/gunicorn_start.bash; user = ubuntu; stdout_logfile = /home/ubuntu/logs/gunicorn_supervisor.log; redirect_stderr = true; … -
Change model form field to text input widget
I want to change the 'trans_recipient' field widget from being a dropdown, into being a text-input field. In the case of a large I've tried the following : class SafeTransactionForm(forms.ModelForm): ''' SafeTranSactionForm ''' trans_recipient = forms.CharField(widget=forms.TextInput(attrs={'class': 'special'})) class Meta: model = SafeTransaction fields = [ 'trans_recipient', 'subject', 'arbitrator_name', 'payment_condition', 'amount_to_pay'] That produces this : and although the widget itself has changed, actually trying to use it produces a value error as such : without my incorrect one-line attempt at changing the widget : class SafeTransactionForm(forms.ModelForm): ''' SafeTranSactionForm ''' class Meta: model = SafeTransaction fields = [ 'trans_recipient', 'subject', 'arbitrator_name', 'payment_condition', 'amount_to_pay'] the dropdown: I've tried playing around with syntax, trying to update the widget within the meta class, I've mostly ended up with syntax errors and I've not been able to find examples of this specific case after some Google searches. Insight and explanations are very much welcome and appreciated. -
Making axios request to django
I have a complex problem in sending and receiving data in react to django with axios. I'm not using REST API . this is my Handel function which is related with my signup form tag and after each click on submit button this function executes: HandelSignUp(e){ e.preventDefault(); let Username = this.refs.username.value; let Pass = this.refs.pass.value; let Email =this.refs.email.value; axios({ url:'http://127.0.0.1:8000/signupAuth/', mothod:'post', data:{ username:this.Username, pass:this.Pass, email:this.Email }, headers: { "X-CSRFToken": window.CSRF_TOKEN, "content-type": "application/json" } }).then(respons =>{ console.log(respons); }) .catch(err =>{ console.log(err); }); and also this is my django urls.py : urlpatterns = [ path('signupAuth/',ReactApp_View.signupRes), ] ReactApp_View is my views.py in ReactApp file wich i imported correctly. ok now let's see my views.py : def signupRes(request): body_unicode = request.body.decode('utf-8') data = json.loads(myjson) return HttpResponse(request.body) after all when i fill my signup fields and then click on button i see this massage in cnsole log of my browser: Failed to load http://127.0.0.1:8000/signupAuth/: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. what should i do? and an extra question : what happen in the given url in my axios? -
How to order django queryset using the Choices displayed label?
Is it possible to order the query set by choices displayed label? If not, can you please advise on how to achieve this? Or is there a way to create a custom ordering? Thanks in advance! Choices C_TYPES = Choices( ('ac_sm', 'ac_sm', _('Ta-Class - Small')), ('ac_md', 'ac_md', _('Ta-Class - Medium')), ('ac_lg', 'ac_lg', _('Ta-Class - Large')), ) Model class FactoryLeadType(): c_type = models.CharField( _('Chiller Type'), choices=C_TYPES , default=C_TYPES .ac_sm, max_length=50, ) class Meta: ordering = ( `get_c_type_display()` ) -
Django failing to load 400.html
I've defined custom templates for errors 400, and 404 for my Django project. When I try to access the production version of my site, the error 404 template is correctly loaded for missing pages. However, if I send a bad request to my Apache/Django server (e.g. http://mysite.example.com/%), the template for the error 400 is not loaded, instead, the regular Apache error page is rendered: Bad Request Your browser sent a request that this server could not understand. Apache/2.4.18 (Ubuntu) Server at mysite.example.com Port 80 Is apache relaying this request to Django at all, or do I need to define handler400 in my Django project in order for this to work (though I didn't have to do that for the 404.html)? -
Django Rest Framework: Generate BrowsableAPIRenderer form in function-based view
Is it possible to annotate a DRF function-based view to display an interactive form based on a Serializer? My view doesn't require the use of a Model, so I feel like class-based Views/ViewSets aren't the right approach. This sample code produces a working "BrowsableAPI", but with a generic JSON text field: @api_view(http_method_names=('POST', )) @renderer_classes((JSONRenderer, BrowsableAPIRenderer)) def push_notifications(request: Request, format=None) -> Response: serializer = PushNotificationSerializer(data=request.data) serializer.is_valid(raise_exception=True) params = serializer.data # ... return Response() I'd like the form it produces to use the serializer. (As browsable documentation.)