Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Simplest Way to Run Matlab Script with Django
I would like to integrate a MATLAB script into a website I built with Django. The script accepts a few parameters and returns a table to the user. I am a novice Django user. I would like to know the simplest and fastest way to execute my MATLAB script using Django and return the results to the user. From what I have read online, it appears there are a few options: 1.) execute script using octave (free so I wouldn't need to pay for MATLAB license for the server) 2.) compile my MATLAB function as python library, write a python script with MATLAB function, and execute the script server-side using django and 3.) compile the MATLAB function as a standalone application and run that application on the server (unclear to me how exactly this would work). There are probably more options I am missing and I would appreciate recommendations on the simplest way to run a MATLAB script on a Django site. Also, the script is fast to execute and takes a 5< seconds to run on my computer, so I think I would not need to use a distributed task queue system like Celery. -
Django site creating a link from html page to another app's main html page
I have an index page in a django project that has (in it's header.html page) a navigation bar. I want the navigation bar to actually work ...currently when I click on 'teachers' in the nav bar I get an error. The code in header.html (which has the nav bar) </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item mx-0 mx-lg-1"> <a class="nav-link py-3 px-0 px-lg-3 rounded js-scroll-trigger" href="/teachers/teachers.html">Teachers</a> </li> </div> The link above in question is: href="/teachers/teachers.html">Teachers The file path/structure of where the teachers.html page is: C:\Users\User\Desktop\rast\teachers\templates\teachers The error: Using the URLconf defined in website.urls, Django tried these URL patterns, in this order: admin/ admin/ header/ [name='header'] [name='index'] teachers/ The current path, teachers.html, didn't match any of these. My question is - what do I need to write in the header.html page (or do I need to dos something else?) to get the nav bar button 'teachers' to go to the teachers.html page. -
Wagtail making pages expire
Is there a management command or something I should be running to make wagtail pick up expired pages? Example: I go into the admin dashboard and change the expiration time (not through the wagtail admin). Wagtail doesn't pick up that this post becomes expired / change the expired boolean to True. Since this is a non-editable field that isn't changeable through admin. Yes, I can mke my own but I'm curious as to why wagtail doesn't pick this up. -
Django: How to update user model without updating user password field
I'm trying to create a user update endpoint that only updates select fields of a user. My currently implementation is to save the model with ModelForm's save method but I've also tried with the base model save method. My request body doesn't contain a password field and I don't have a password field in my UserForm, however I'm unable to maintain the current session or logout and log back in with the current user after executing an update. I'm nearly positive this is because Django is changing my password somewhere during the update process. Other pertinent information: I'm using Django (not Django Rest Framework). I have a custom user model. I know I can solve this issue by using serializers with DRF but it seems hacky to use that for this issue alone. My endpoint looks like this: def saveAccountData (request): resp = {} if request.method == 'POST': form = UserForm(request.POST, instance=request.user) if form.is_valid(): form.save() resp['result'] = 'User updated' return HttpResponse( json.dumps(resp), status=200 ) else: return HttpResponse( json.dumps(form.errors), status=422, ) My Form looks like this: class UserForm(forms.ModelForm): class Meta: model = User fields = ['email', 'name', 'is_active', 'is_admin'] def save(self, commit=True): user = super(UserForm, self).save(commit=False) user.name = self.cleaned_data['name'] if commit: … -
how to integrate chatbot created with django in app mobile ionic(version >2)?
What do I need to do in ionic for it to use chatbot? did not want to use solutions like DialogFlow. I need to create something native to the company I work for. but, I do not know how to do integration with ionic. -
SharePoint API Call for File Upload
I'm building an app in Django and trying to upload a file to a SharePoint Online Site but I'm sure I've (at least) got the url wrong for the API call. I have the appropriate permissions allotted to the app in dev.microsoft.com but get back a 500 response when I try to upload. this is the basic api call I'm trying to use PUT /sites/{site-id}/drive/items/{parent-id}:/{filename}:/content I'm kind of going by these 2 resources to build the url but not sure of the site-id or parent-id. For the {YourSharepointTenant} i got the tenant-id from the Azure Portal under properties. Its a long list of characters that I omitted from my code i posted here https://www.coderedcorp.com/blog/uploading-files-to-sharepoint-with-django-and-pyth/ https://docs.microsoft.com/en-us/onedrive/developer/rest-api/api/driveitem_put_content Here is my code def save(self, *args, **kwargs): # Get the authenticated user credentials from office365-allauth social = request.user.social_auth.get(provider='office365') access_token = social.extra_data['access_token'] # build our header for the api call headers = { 'Authorization' : 'Bearer {0}'.format(access_token), } # build the url for the api call # Look at https://dev.onedrive.com/items/upload_put.htm for reference url = 'https://{YourSharepointTenant}.sharepoint.com/sites/ITSupport/drive/root:/' + design_document + ':/content' # Make the api call response = requests.put(url, data=open(design_document, 'rb'), headers=headers) return response super(LaserMaskDesign, self).save(*args, **kwargs) -
Do a manual orderby for a queryset in Django
I am using Django 1.11 and I am trying to figure out a way to change the order of a queryset manually. Here is my setup: models.py class Channel(models.Model): channel_no = models.CharField(max_length=4, unique=True) def __str__(self): return self.channel_no I have an array of channel numbers that I wish to use for my order: channel_order = ['2','4','6','8','10','1','3','5','7','9'] How can I use that order for a queryset? -
Django getting "first_name" is invalid keyword argument for this function" TypeError when creating an instance of my model class
Using Django 1.11 and django-pyodbc-azure latest version if it is relevant. I am new to Django and have been following along the 1.11 tutorial without any issues until this, and I am incredibly confused. Here is my models.py: from django.db import models # Create your models here. class Player(models.Model): first_name = models.CharField(max_length=20, name='First Name') last_name = models.CharField(max_length=20, name='Last Name') def __str__(self): return '{}, {} ({})'.format(self.last_name, self.first_name, self.id) class Game(models.Model): players = models.ManyToManyField(Player, name='Players') def __str__(self): return ' vs. '.join(self.players) class Round(models.Model): GIN = 'GI' UNDERCUT = 'UN' KNOCK = 'KN' ENDING_ACITONS = ( (GIN, 'Gin'), (UNDERCUT, 'Undercut'), (KNOCK, 'Knock'), ) game = models.ForeignKey(Game, on_delete=models.CASCADE, name='Parent Game') winner = models.ForeignKey(Player, on_delete=models.CASCADE, name='Winning Player') points = models.IntegerField(name='Points Awarded') end = models.CharField(max_length=2, choices=ENDING_ACITONS) def __str__(self): return '{} awarded {} points via {}'.format(self.winner, self.points, self.end.name) Now when I run manage.py shell and type: from game.models import * bobby = Player(first_name='Bobby', last_name='Fisher') I am met with this error: Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\mteper\PycharmProjects\GinRummy\venv\lib\site-packages\django\db\models\base.py", line 571, in __init__ raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0]) TypeError: 'first_name' is an invalid keyword argument for this function Any insight would be greatly appreciated, as, like … -
How to start periodic tasks by calling function in Celery with Django
I was working with period tasks and by their documentation I have successfully create one simple program but those period task execute only when app is get configured. I am talking about this decorator @app.on_after_configure.connect What I am trying to do is I need to execute one period task when I call any particular function so that it get scheduled and then worked accordingly. I tried this but no success: @app.task(name="project.tasks.report") def report(): app.add_periodic_task(10.0, say.s(2, 3), name='add every 10') print('I passed') Here I was trying to call say function with 2 parameters in periodic way for every 10 seconds but with this code snippet it is not working. So what I am really trying to do is: Call report function from views.py in Django Add this periodic task and execute it every x seconds. -
Multiple inheritance in Django Models using abstract classes calling attributes between classes
I have 2 abstract classes Note and Meta that I want to use on multiple models. Also a class Post. class Note(models.Model): def save(self, *args, **kwargs): # get the initial state, if is created or updated state = self._state.adding ......... if self.__original_is_active: action(created_by ...) class Meta: abstract = True class Meta(models.Model): created_by = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, related_name='%(app_label)s_%(class)s_created_by', on_delete=models.CASCADE) class Meta: abstract = True class Post(Meta,Note): is_active = models.BooleanField(default=False) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__original_is_active = self.is_active As you can see, Note is using attributes defined on Post(is_active) and Meta(created_by) If I keep def init on Post I get the following error: 'Post' object has no attribute '_Note__original_is_active' If I move def init on the parent Note everything is ok, is working but I want to use original_is_active, later in the Post class on his own def save, or even in another abstract class, so I'm thinking maybe is a better solution. If in init I reverse the order of instructions: def __init__(self, *args, **kwargs): self.__original_is_active = self.is_active super().__init__(*args, **kwargs) I get the error: Post object has no attribute '_state' _state is from models.Model Meta and Note are not related in anyway, in Note I just get the user from created_by(which … -
Django: all identical UUIDs after migration
I have a mixin to add an UUID to any model: class UUIDable(models.Model): uuid = UUIDField(db_index=True, default=uuid.uuid4, editable=False) class Meta: abstract = True I have an existing database with Article objects inside. I just added an uuid field to the Article class using the mixin above. After running the migration, all my articles now have the SAME UUID. I expected all the objects to have a different UUID. Why? Here is the automatically created migration file: class Migration(migrations.Migration): dependencies = [ ('products', '0009_auto_20171218_1630'), ] operations = [ migrations.AddField( model_name='article', name='uuid', field=models.UUIDField(db_index=True, default=uuid.uuid4, editable=False), ), ] -
Django get_queryset method of a custom model manager has no effect on other built-in methods(get, filter, etc.)
I have created a model manager with a method that adds some string to the certain field and my goal is to apply this method every time when objects called. As I understand, this can be achieved by using the get_queryset method in the custom manager, however this only works if I call SomeModel.objects.all(). If I try to apply some filter, or get object by parametr, it simply returns me original data without my method applied. models.py: class BaseModelQuerySet(models.QuerySet): def edit_desc(self, string): if self.exists(): for obj in self: if 'description' in obj.__dict__: obj.__dict__['description'] += string return self class BaseModelManager(models.Manager): def get_queryset(self): return BaseModelQuerySet(self.model, using=self._db).edit_desc('...') class BaseModel(models.Model): objects = BaseModelManager() class Meta: abstract = True Output in django shell: >>> SomeModel.objects.all()[0].description 'Some example of description...' >>> SomeModel.objects.get(id=1).description 'Some example of description' People, what am I doing wrong, please help. Thanks thousand times in advance! -
I'm trying to print a html output from a oracle query in django
Giving a query from oracle using import cx_oracle on Django/python, I'm trying to print the result of the query in a HTML page but instead of printing this-> Série: ('FR2017', 207253, '110511', 'person name', 333.0, 62000001, 'ECO ABDOMINAL', 45.0, 5.0) Número: ('FR2017', 207253, '110511', 'person name', 333.0, 62000001, 'ECO ABDOMINAL', 45.0, 5.0) GTS: ('FR2017', 207253, '110511', 'person name', 333.0, 62000001, 'ECO ABDOMINAL', 45.0, 5.0) Nome: ('FR2017', 207253, '110511', 'person name', 333.0, 62000001, 'ECO ABDOMINAL', 45.0, 5.0) Valor: ('FR2017', 207253, '110511', 'person name', 333.0, 62000001, 'ECO ABDOMINAL', 45.0, 5.0) How can I print like this? -> Série: FR2017 Número: 207253 Gts: 110511 Nome: person name Valor: 45.0 -
Error saving tags in Django Taggit
I have my models.py as class TaggedActionsBefore(GenericTaggedItemBase): tag = models.ForeignKey(Tag, related_name="%(class)s_emotionsbefore") class TaggedActionsAfter(GenericTaggedItemBase): tag = models.ForeignKey(Tag, related_name="%(class)s_emotionsafter") class ActionJournal(models.Model): situation = models.TextField() actions_before = TaggableManager(blank=True, through=TaggedActionsBefore, help_text="") actions_after = TaggableManager(blank=True, through=TaggedActionsAfter, related_name="actionsafter", help_text="") I am getting the following error when I am trying to save tags get() returned more than one Tag -- it returned 2! through a form which is model a model form of the ActionJournal model. Please let me know what I am doing wrong. -
Deployment of Django in local network while continuing development
The question is in the title. I need to deploy a Django application in a local network (i still don't know how to do but i suppose it's quite easy) but i still need to develop it. My question is how to do to allow users to use the application while i'm still developing it ? Is it a solution to keep to versions of the application, one deployed and one in development ? In this way, I can replace the application deployed by the newly developed one when I finish coding it. Another question concerns the database, can I still modify the database if I just add new models without touching existing ones ? Thank you in advance, -
Start testing already existing Django project
I just read the whole Django documentation about testing and I need soon to start testing an existing project. The project, a dashboard, is pretty big and I was not involved in the development phase (yeah, it sucks). There will be unit tests and integration tests (with Selenium). Here are few questions: Is there any suggestion to start in the best way to test an existing project? Which framework / tools should I use? (actually using only 'coverage' and 'mommy_model') Should I start from the unit tests? Should I test the models first? I feel very disoriented because it's a whole new world for me, but I'm really exited at the same time. Hope some experienced tester can show me the right path. -
What are the difference and advantages among django and flask frameworks in python?
What is Django used for? What is Flask and its uses? Are there any similarities/differences? When should one prefer one over the other? -
Token_for_business to check the user's presence on Facebook
Is it possible to check if a user is on Facebook with token_for_business? In the database, the column holding the records for token_for_business exists and contains randomly written token_for_business. But I do not know which ones are real. I'm looking for a verification action for this. -
Max_length in Django CharFields
The Django docs indicate that: The max_length is enforced at the database level and in Django’s validation. What, exactly does this mean? I have a routine to parse an input CSV file to create some models, and an over-length Name field got in there along the way as I created objects using: new_standard = Standard.objects.create(Name=lname,ShortName=sname,calcmethod=method,Description=descr,course=course,Order=stdnum) new_standard.save() The error was only raised later, as the user tried to edit the object using a form (which wouldn't validate). When using the same form to create objects, the input field won't allow typing past the 30th character, but my manual method seems to allow the over-length field to be created. How do I avoid this (apart from manually truncating strings after checking field lengths, which I could do, but which seems like a lot of hassle - seems like I could handle it in the form or DB)? Now that I have some of these time bombs in my DB, what's the easiest way to get rid of them? -
Unit test in Django: using self.assertIn() to find text in key/value pair
I'm trying to write a unit test for my Django app using self.assertIn() This is my unit test: def test_user_get_apps_meta(self): myuser = User.objects.get(email='theemail@gmail.com') tagline = 'the text' self.assertIn(tagline, myuser.get_apps()) The result of myuser.get_apps() is a list of dictionaries. In one of those dictionaries is indeed the tagline text I'm looking for: 'the text' But I'm getting an error when I run the test: self.assertIn(tagline, myuser.get_apps()) AssertionError: 'the text' not found in [{'logo_app_alt': 'the text', '...},{},{}] Am I not using self.assertIn() correctly? Is there a way to check if certain text is the value of a key/value pair in a dictionary? -
Python web development framework for a dashboard application
I need help in choosing a Python web framework for a rewrite of a dashboard application. I listed all frameworks from the official community list that are full-stack and have had an update since January 2017. I've removed all frameworks from the list that had very little stars and contributors on Github, weren't well-documented and/or had too little in-the-box functionality. I came up with these 4 candidates: Django web2py Tornado CubicWeb The most important requirements for my project are: widgets on the dashboard visualize values in near-real time, received from a LOT of web services, either using polling or WebSockets, using a client side single page application must be possible, I want well-structured code and prefer an MVC web framework, some data (dashboard & widget composition) must be stored in a database on the server the server must be able to read and write files rapidly, and in a private folder, there's a need for user login and sharing of dashboards among users and groups of users, and access rule checking for various pages and functionality I want a framework that has a manageable learning curve. What seems to be the best option? -
Django View Returns 502 Bad Gateway on Google App Engine
I've created an Django app and deployed in on GAE. However, whevever I run the page which executes a script xxx.appspot.com/script, it returns 502 Bad Gateway. As a side note, everything works fine locally, and 502 appears after around 30 seconds (I'm assuming the script simply takes longer than that to execute and the server doesn't wait enough time). My app.yaml is: runtime: python env: flex entrypoint: gunicorn -b :$PORT djangoapp.wsgi resources: memory_gb: 4 views.py (Responsible for rendering the page) def model(request): try: model = joblib.load('static/model.pkl') # run the LONG CODE which runs model predictions, outputs it etc. return render(request, "queries/success.html") except Exception as e: logging.critical(e) return render(request, "queries/fail.html") Now I can come up with 2 issues: 1) Nginx server is not giving enough time to execute the command and spits out the error. 2) The model is not loaded on GAE properly (since it's located in the STATIC directory which maybe doesn't exist on GAE - I'm not sure since I can't see the files used by GAE). In my settings.py, I have defined where to get static files: STATIC_URL = 'https://storage.googleapis.com/django/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [os.path.join(BASE_DIR, "staticfiles"),] TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'templates'),) -
Deploying Django on AWS
I'm looking to deploy a django app on AWS (either elastic beanstalk or through ec2) but after lot's of searching can't actually find a tutorial that works for me. Using http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html I've managed to get my application uploaded but can't find anything about how to create a database for it or manage it properly. (as in I don't know how to access logs for it as I can't see the instance this is running on my aws dashboard) I realise this is a very open ended request but any direction towards an up to date good tutorial on this would be hugely appreciated. -
Get list from two models (With addtional fields). Make Subquery
I have models Reserved and Room (default status is Free). And i want get list of all Rooms. Their statuses is Reserved (I have such table) Free (not price, state) Busy So in short i need to get all Rooms with their status. I don't need status fields and will not add it. No status field in my models. How can i get certain statuses? Shortly model class Room(models.Model): # Default all rooms are Free (Rooms state) number = models.ForeignKey(RoomNumber) expiry_date = models.DateTimeField() class Reserved(models.Model): visitor = models.ForeignKey(Visitor, on_delete=models.PROTECT) room = models.OneToOneField(Room) reserved_date = models.DateTimeField() begin_date = models.DateTimeField() I tried to do Subquery but no result :( reserved = Reserved.objects\ .filter(room=OuterRef('pk'))\ .filter(begin_date=timezone.now())\ .values(count=Count('pk')) Room.objects.annotate(reserved=Subquery(reserved[:1])) If 1 room is Reserved if 0 empty -
Learn about user status with token_for_business on Facebook
I want to delete the random facebook business id that was entered into the database years ago. An idea for that came to mind. Putting business id in the database on the facebook verification test. I entered the Facebook development environment. Here I wanted to test several business_ids in db. But I did not get the result I wanted. In the end, can I check with the token_for_business id to see if the user actually exists?